9
Why in PHP it is possible to call a function before the line in which it was declared?
echo ah(); // 'Ah!'
function ah() {
return 'Ah!';
}
Notice that I called ah()
first, then I declared. Even so, it was executed. But the function theoretically would not exist before that line? So how was it 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 insertion occurs after the function is called, this does not happen, even if inside the include
there is the function called.
index php.
echo ah();
include 'ah.php';
a. php
function ah() { return 'Ah!'; }
That 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
, that doesn’t 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 declaration coming from a
include
?In the first case, PHP analyzes the code only once to know if the function was declared? How was this "magic" done?
First example in IDEONE
I might be wrong, but include in php is different from other languages, it’s actually like it’s a
eval
(in fact he is aeval
) and the "scope" is often different, so much so that theinclude
can even return values.– Guilherme Nascimento