PHP call function from another file with examples

Posted on Aug 29, 2022

Learn how to call a function from another file in PHP

Photo from Unsplash

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

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
function sum(int $x, int $y) {
    return $x + $y;

Just add the parameters when calling the function in another file as follows:

// index.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! 👍

Level up your programming skills

I'm sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.