开发者

Defining a function inside a conditional

开发者 https://www.devze.com 2023-01-13 15:08 出处:网络
Snippet 1 works. Snippet 2 doesn\'t. Why? 1. foo(); function foo() { // do soemething } 开发者_开发技巧

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(); 
0

精彩评论

暂无评论...
验证码 换一张
取 消