What is the processing order of a PHP script?

Asked

Viewed 264 times

6

Example scenario:

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

function hello() {

    return 'World';
}

function world($v) {

    return $v;  
}

Exit:

World
Hello World

Like the PHP process this?

On the example, we can conclude: the echo is before the method, then the PHP does not read line by line in sequence, 'cause if it was that way, he wouldn’t have read the method below to be able to resolve the current line (which is before), correct!?

Doubts:

  • He’s been reading line by line and by positioning in a line that calls a method, it searches that method in every script and stores in memory, and only after back to solve where did you stop?

    • Assuming this is the case, when he finishes searching for the method and solves the line in position, he continues reading the script following the next lines, so on?
  • Very good your doubt, I will research, I was quite interested.

1 answer

7


This is because the interpreter first analyzes the code and then executes. When parsing the code, it will load the functions into memory and then in the execution phase it will run line by line. As the functions have already been loaded, there will be no problem in calling them before your statement.

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 conditionally defined as in the two examples below, your definition needs to be processed before it is called.

It is a process similar to what occurs in Javascript’s Hoisting, where functions are moved to the top of the scope before code is executed:

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

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

  • "When a function is conditionally defined as in the two examples below, its definition needs to be processed before it is called." So if I have a function within a condition (e.g., ìf`), then do I need to have it above ? Because it scans the entire script, stores the functions in "first level" ?

  • "If you use a include with the function and call it before, it will result in Fatal error: Call to Undefined Function" Very interesting. Although practically never give library includes after any script, had never bumped into it !

  • 1

    That’s right. According to the documentation (see the examples there), if the function depends on a condition, it cannot be called before.

  • 2

    Escape from conditionally defining functions, @RBZ. In any language.

  • 1

    Very interesting! Congratulations on the question and the answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.