Function definition inside conditional

Fragment 1 produced. Fragment 2 - no. Why?

1.

foo();

function foo()
{
    // do soemething
}

2.

foo();

if(!function_exists("foo"))
{
    function foo()
    {
        // do soemething
    }
}
+3
source share
2 answers

See http://www.php.net/manual/en/functions.user-defined.php :

Functions do not have to be defined before they are referenced, unless the function is conditionally defined [...] Its definition must be processed earlier called.

+11
source

You try to execute foo () before testing to make sure it is defined or not (and subsequently defines it)

if(!function_exists("foo")) 
{ 
    function foo() 
    { 
        // do soemething 
    } 
} 

foo(); 
+6
source

Source: https://habr.com/ru/post/1761484/


All Articles