Functions don't need to be defined before they are called.
In this example, function
printMe()
is defined after it's called but it works without errors
echo printMe();
function printMe() {
return 'Print some text';
}
Exception is
conditional function
.
In this example function
foo()
will not be defined until the
if ($makefoo)
conditional statement gets executed
$makefoo = true;
/* We can't call foo() from here
since it doesn't exist yet,
but we can call bar() */
// foo();
bar();
if ($makefoo) {
function foo()
{
echo "I don't exist until program execution reaches me.\n";
}
}
/* Now we can safely call foo()
since $makefoo evaluated to true */
if ($makefoo) foo();
function bar()
{
echo "I exist immediately upon program start.\n";
}
Functions within functions.
Function
bar()
will not be defined until the function
foo()
is executed
function foo()
{
function bar()
{
echo "I don't exist until foo() is called.\n";
}
}
/* We can't call bar() yet
since it doesn't exist. */
// bar();
foo();
/* Now we can call bar(),
foo()'s processing has
made it accessible. */
bar();
Note: All functions in PHP have the global scope - they can be called outside a function even if they were defined inside and vice versa