According to PHP manual calling a user-defined function prior to its definition doesn't produce an error except:
When a function is defined in a conditional manner... Its definition must be processed prior to being called.
Example:
bar();
$makefoo = true;
if ($makefoo) {
function bar() {
echo "I don't exist.
";
}
}
Throws a Fatal error:
Fatal error: Uncaught Error: Call to undefined function bar() in...
With above explanation I suppose below code to produce the same error:
foo();
bar();
function foo() {
$makefoo = true;
if ($makefoo) {
function bar() {
echo "I don't exist until foo() is called.
";
}
}
}
But it doesn't. What am I missing in manuals that describes this behavior?
foo();
bar();
function foo() {
$makefoo = true;
if ($makefoo) {
function bar() {
echo "I don't exist until foo() is called.
";
}
}
}
PHP code is executed in two passes: first the parsing and compilation step, then the runtime. Plain functions like foo
can be defined at parse time; they're unconditional and not dependent on runtime information.
So function foo
is defined at parse time, then at runtime foo()
is called, which creates function bar
, so then you can call bar()
right afterwards.