PHP call function from another file with examples
To call a function from another file in PHP, you need to import the file where the function is defined before calling it.
You can import a PHP file by using the require statement.
For example, suppose you have a file named library.php with the following content:
// library.php
function greetings() {
echo "Hello World!";
}
To call the greetings() function from another file, you need to import the library.php file as shown below:
// ๐ import the PHP file
require "library.php";
// ๐ call the function
greetings();
By using the require statement, PHP will evaluate the code in that file before running the current file.
The same method works when you have a function with parameters as well:
// library.php
<?php
function sum(int $x, int $y) {
return $x + $y;
}
Just add the parameters when calling the function in another file as follows:
// index.php
<?php
require "library.php";
// ๐ call the function with parameters
$n = sum(10, 9);
echo $n; // 19
Now you’ve learned how to call a function from another file in PHP. Nice work! ๐
More PHP tutorials
See allPHP
PHP form validation basic example
Dec 22, 2022
PHP
PHP validate email address (with code examples)
Dec 22, 2022
PHP
How to redirect using PHP with code examples
Dec 22, 2022
PHP
Handling form data using PHP (GET and POST)
Dec 21, 2022
PHP
How to fix Wordpress PHP error missing MySQL extension
Dec 21, 2022