Defining a function inside a conditional
Snippet 1 works. Snippet 2 doesn't. Why?
1.
foo();
function foo()
{
// do soemething
}
开发者_开发技巧
2.
foo();
if(!function_exists("foo"))
{
function foo()
{
// do soemething
}
}
See http://www.php.net/manual/en/functions.user-defined.php:
Functions need not be defined before they are referenced, except when a function is conditionally defined [...] Its definition must be processed prior to being called.
You're trying to execute foo() before testing to see whether it's defined or not (and subsequently defining it)
if(!function_exists("foo"))
{
function foo()
{
// do soemething
}
}
foo();
精彩评论