What is the order of processing a PHP script?

7

Example scenario:

echo hello();
echo '<br>';
echo 'Hello ' . world('World');

function hello() {

    return 'World';
}

function world($v) {

    return $v;  
}

Output:

World
Hello World

How does PHP process this?

About the example, we can conclude: echo is before the method , so PHP does not read row by line sequentially , so if it was that way, it would not have read the method below to be able to resolve the current (correct) line!?

Questions:

  • It has been reading line by line and when positioning on a line that calls a method, it searches that method in every script and stores it in memory strong>, and only then back to solve where did it stop?

    • Assuming that this is the way, when you finish fetching the method and resolving the line in position, it continues to read script following the next lines, and so on?
asked by anonymous 08.05.2018 / 18:27

1 answer

8

This is because the interpreter first parses the code and then executes it. When parsing the code, it will load the functions into memory and then in the run phase it will run line by line. Since the functions have already been loaded, it will not be a problem to call them before your declaration.

From the PHP documentation :

  

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

     

When a function is defined conditionally as in the two examples   below, your definition needs to be processed before it is called.

It is a process similar to what happens in JavaScript hoisting, where functions are moved to the top of the scope before the code is executed:

    teste();
    function teste(){
       console.log("ok");
    }
    // imprime no console: ok

But this also only works on code from the same file. If you use an include with the function and call it before, it will result in Fatal error: Call to undefined function .

    
08.05.2018 / 19:11