Note that PHP doesn't really support "nested functions", as in defined only in the scope of the parent function. All functions are defined globally. See the docs.
Not sure what the author of that code wanted to achieve. Definining a function inside another function does NOT mean that the inner function is only visible inside the outer function. After calling x() the first time, the y() function will be in global scope as well.
function inside a function or so called nested functions are very usable if you need to do some recursion processes such as looping true multiple layer of array or a file tree without multiple loops or sometimes i use it to avoid creating classes for small jobs which require dividing and isolating functionality among multiple functions. but before you go for nested functions you have to understand that
child function will not be available unless the main function is executed
Once main function got executed the child functions will be globally available to access
if you need to call the main function twice it will try to re define the child function and this will throw a fatal error
so is this mean you cant use nested functions? No, you can with the below workarounds
first method is to block the child function being re declaring into global function stack by using conditional block with function exists, this will prevent the function being declared multiple times into global function stack.
function myfunc($a,$b=5){
if(!function_exists("child")){
function child($x,$c){
return $c+$x;
}
}
try{
return child($a,$b);
}catch(Exception $e){
throw $e;
}
}
//once you have invoke the main function you will be able to call the child function
echo myfunc(10,20)+child(10,10);
and the second method will be limiting the function scope of child to local instead of global, to do that you have to define the function as a Anonymous function and assign it to a local variable, then the function will only be available in local scope and will re declared and invokes every time you call the main function.
function myfunc($a,$b=5){
$child = function ($x,$c){
return $c+$x;
};
try{
return $child($a,$b);
}catch(Exception $e){
throw $e;
}
}
echo myfunc(10,20);
remember the child will not be available outside the main function or global function stack