Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP workflow - order of execution of functions

I'm wondering about order of interpreting function declarations by PHP engine. I don't know why somethimes PHP shows Call to undefined function fatal error and somethimes interpreter see the function without problem.

Let's suppose my code is:

echo theRest(4,3);

function theRest($a, $b)
{
   return $a % $b;
}

See that function is declared after invocation and this works proper. It means that PHP reads whole file before interpretation?

Another example:

echo theRest(4,3);

include('test2.php');

test2.php

function theRest($a, $b)
{
    return $a % $b;
}

Here i'm getting the Fatal error: Call to undefined function theRest(). Why is that?

like image 386
webrama.pl Avatar asked Mar 11 '13 09:03

webrama.pl


2 Answers

means that PHP is reading whole file before interpretation?

yes, PHP parses one file at a time. And "include" is a statement, not something that happens at compile time, so the included file is parsed as soon as the include line is reached. Function definition on the other hand are not statements and are processed at compile time, except when they are located within a control structure. This is why the following works:

if (!function_exists('ucwords')) {
    function ucwords($str) {
        //...
    }
}

So every function and class definition in a file that has been parsed and resides outside of a control structure is available immediately.

like image 58
Fabian Schmengler Avatar answered Oct 28 '22 09:10

Fabian Schmengler


When PHP reads a file, it compiles it to bytecode (compile time), then executes it (execution time / runtime).

Unconditional function declarations are read at compile time, so that functions are already known when your code is executed.

Includes, on the other hand, are executed at execution time, so functions defined in the include file are not available before the include() itself is executed. Includes cannot be performed at compile time, since the argument may be dynamic (e.g. include $path_to_file;) and depend on the include_path setting that may be modified by your code.

The documentation is quite clear about that:

Functions need not be defined before they are referenced, except when a function is conditionally defined as shown in the two examples below.

When using include(), your function is de-facto conditionally defined (for example, include "foo.php"; can include one file or the other depending on the include_path setting).

like image 40
Ferdinand Beyer Avatar answered Oct 28 '22 09:10

Ferdinand Beyer