Nested function weirdness on PHP [duplicate]
-
26-06-2021 - |
Frage
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?
Lösung
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()
before bar()
, bar()
will not yet exist.
You can test with function_exists()
before creating it:
function foo(){
// Don't redefine bar() if it is already defined
if (!function_exists("bar")) {
function bar(){
}
}
}
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.
Andere Tipps
Functions are always created in the global scope, but only when their definition is executed.
The function "inside" is only declared when the outer function is called.
In your first example, you don't call foo()
, therefore bar()
is never declared.
In your second example, you call foo()
twice, so bar()
is declared twice.
In the first example, bar
is declared in the function foo
. So calling bar
makes no sense without first calling foo
since its definition hasn't been executed yet. In the second example, you are calling foo
twice so the bar
function gets declared twice.