Possible Duplicate:
nested functions in php throws an exception when the outer is called more than once
why does
function foo(){
function bar(){
}
}
bar();
return fatal error on nonexistent function bar
while
function foo(){
function bar(){
}
}
foo();
foo();
gives fatal error on duplicate declaration for bar()?
does php handle the function as global or in the parent’s function scope?
The function itself is defined at global scope, even if it was defined inside another function. In the first case, if you don’t call
foo()beforebar(),bar()will not yet exist.You can test with
function_exists()before creating it:However, since the nested function is not scoped to the outer function, the use cases for defining a function inside another function are somewhat limited. Furthermore, it introduces some odd side-effects into your code which can become difficult to understand and maintain. Consider if you really want to do this, and rethink your reason for doing so if necessary. You might be better served by namespaces or classes/objects if what you’re looking for is scope limits.