This code produces the result as 56.
function x ($y)
{
function y ($z)
{
return ($z*2);
}
return($y+3);
}
$y = 4;
$y = x($y)*y($y);
echo $y;
Any idea what is going inside? I am confused.
This code produces the result as 56.
function x ($y)
{
function y ($z)
{
return ($z*2);
}
return($y+3);
}
$y = 4;
$y = x($y)*y($y);
echo $y;
Any idea what is going inside? I am confused.
(4+3)*(4*2) == 56
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.
Your query is doing 7 * 8
x(4) = 4+3 = 7
and y(4) = 4*2 = 8
what happens is when function x is called it creates function y, it does not run it.
X returns (value +3), while Y returns (value*2)
Given a value of 4, this means (4+3) * (4*2) = 7 * 8 = 56
.
The placing of functions here doesn't make any difference. Functions are not limited in scope, which means that you can safely 'nest' function definitions, while still being able to call them anywhere in the file. Basically, the code you posted is no different than
function x ($y)
{
return($y+3);
}
function y ($z)
{
return ($z*2);
}
Except for the fact that it's a lot less readable.
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.