Why would PHP allow nesting functions?
<?php
function foo() {
function bar() {
return "bar";
}
return "foo";
}
print foo();
print bar();
.. is valid PHP.
But:
I ran into this today, because I forgot a closing bracket somewhere, and had one too many further down. The code was valid and no errors thrown; but it all started acting really weird. Functions not being declared, callbacks going berserk and so on. Is this a feature, and if so, to what purpose? Or some idiosyncrasy?
ANSWER: commentor points out that this is a duplicate of What are php nested functions for.
A nested function can access other local functions, variables, constants, types, classes, etc. that are in the same scope, or in any enclosing scope, without explicit parameter passing, which greatly simplifies passing data into and out of the nested function. This is typically allowed for both reading and writing.
A function inside the body of another function is called nested function.
A function is a piece of code that takes another input in the form of a parameter, processes it, and then returns a value. A PHP Function feature is a piece of code that can be used over and over again and accepts argument lists as input, and returns a value.
A nested function is a function defined inside the definition of another function. It can be defined wherever a variable declaration is permitted, which allows nested functions within nested functions. Within the containing function, the nested function can be declared prior to being defined by using the auto keyword.
In PHP you can define functions, run-time constants and even classes conditionally. This allows you to define different functions / constants / classes depending on the circumstances.
Simply example: Define the String\Length
function depending on whether multibyte support is turned on or off in your application.
namespace String;
if (\MULTIBYTE_MODE) {
function Length($string) {
return strlen($string);
}
} else {
function Length($string) {
return mb_strlen($string);
}
}
Nested functions are only a special case of conditional function definition.
Note that the order is important here; you cannot call bar() before calling foo() in your example. The logic here appears to be that the execution of foo() defines bar() and puts it in global scope, but it's not defined prior to the execution of foo(), because of the scoping.
The use here would be a primitive form of function overloading; you can have your bar() function perform different operations depending upon which version of foo() declares it, assuming of course that each different version of foo() indeed defines a bar() function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With