Skip to content
Advertisement

Fatal Undefined Function Error with included files in PHP

Here is the statement from PHP manual:

When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.

I have a file called inc.php with the following function definition:

function echo_name($name) {
  echo $name;
}

Another file called main.php has the following code (Version 1):

// This call throws an error
echo_name('Amanda');

require_once("inc.php");

// This call works
echo_name('James');

If instead of using require_once, I directly put the function all calls work (Version 2):

// This call works
echo_name('Amanda');

function echo_name($name) {
  echo $name;
}

// This call works
echo_name('James');

What does PHP manual mean by

all functions and classes defined in the included file have the global scope.

when the code in Version 1 fails but Version 2 works?

Thanks.

Advertisement

Answer

PHP is an interpreted language, means (removing all not currently needed details) that PHP will interpret your code mostly line by line. Function, class declarations are interpreted before actual code execution (on pre-compilation stage) but require and include directives are executed only when they really called in code.

In your first example, echo_name function will not be declared before require statement and that’s why you receive this error.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement