tags:

views:

627

answers:

4

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  A: 
(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.

Lukáš Lalinský
Thanks, so inner function does not get called.
openidsujoy
Of course it does, that's what results in the `(4*2)` part.
Lukáš Lalinský
When X is called, the inner function is defined - not called. Thus the result. That's the hairy part about functions in functions =)
thephpdeveloper
@Lukas - i bet the asker was referring about the part when function `y()` is in `x()`
thephpdeveloper
Oh, well, I should refer to the same docs then, which explains also the syntax for *calling* functions. :)
Lukáš Lalinský
+1  A: 

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.

Mike Valstar
Just wanted to add that this isn't really good practice. You will also notice that if you use $y = y($y)*x($y); that the code will die because x hasn't been created. Coding like this will just lead to errors and confusion.
Michael Mior
yes thats true; personally I have only ever used this once in practice to case in for different styles of magic quotes. although that was in an if statement instead of a function ()
Mike Valstar
+3  A: 

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.

Duroth
Another difference is that if you have function y inside function x, and you call function x twice, you will get an error for re-declaring function y. (If you really need to this, you need to surround function y with a check for if (function_exists('y')) { ... )
Eugene M
@Eugene M: I never even knew that.. Thanks for pointing it out! (Just tested it myself, after reding your comment.)
Duroth
+2  A: 

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.

Anti Veeranna
+1 That last sentence answers the question very succinctly.
GZipp
Also, definining y() inside x() means that x() can only be called once. You will get the 'function already defined' fatal error when calling x() the second time.
Anti Veeranna