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.phpThat 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