Why in PHP is it possible to access functions before the line they were declared?

8

Why in PHP is it possible to call a function before the line where it was declared?

echo ah(); // 'Ah!'

function ah() {
     return 'Ah!';
}

Notice that I called ah() first, then declared. Even so, she was executed. But the function theoretically would not exist before this line? So how was she called?

How does this happen internally? I thought the script would run sequentially, but calling a function that is declared after that gives me another understanding.

This seems to work only when the statement is made in the same script.

When a script is added after the function call, this does not happen, even if within the include function call exists.

index.php

echo ah();

include 'ah.php';

a.php

function ah() { return 'Ah!'; }

This would generate:

  Uncaught Error: Call to undefined function ah () in index.php

That is: I can call a function before the declaration line, as long as it is in the same file. If it is with include , this does not work.

Why?

  • What is the difference between the function declared after the call that is in the same script for the function that was called before the statement coming from a include ?

  • In the first case, does PHP only parse the code once to see if the function has been declared? How did this "magic" come about?

First example on IDEONE

    
asked by anonymous 05.12.2016 / 16:59

1 answer

9

I can not state with authority on the exact functioning of PHP, but I know about compilers ( an interpreter is still a compiler ), and everyone I know that allows the function to be called before being declared does the process of lexing and parsing in two steps.

First it analyzes all statements, creating a public symbol tables that can be used in script , and ignores what is in the body of the functions. Then it analyzes the algorithms contained in the functions, so when the call occurs, the statement is already known. Simple as that.

The first step analysis does not consider the inclusion of files, so it does not resolve the symbols contained in this new file. Nor could it since include is resolved dynamically (at execution time). It may even be conditional, so only after analysis of the algorithm and the actual execution is it can decide whether to include it or not, so it can not be solved in the first step. Not even in the second, it is resolved in execution.

C and Pascal are some of the few exceptions that do not do in two steps. C ++ does in several, and even does not allow the declaration out of order. It could, but maybe it could be confusing because of include .

    
05.12.2016 / 17:14