2 same variable name , different value

Hi guys,

I am just trying some stuff out in PHP.

Can someone explain me this:

function x ($y) {
    function y ($z) {
        return ($z*4);
    }
    return($y+5);
}

$y = 3;
$y = x($y)*y($y);

echo $y; //outputs 96

My question is, i got 2 variables $y, how does the function puts in the value 3 when I changed $y from a number to a function.

Well, likely this is a bug of some sort in PHP. Your code is well-formed as they say for the PHP parser. But, the side effect of the parser gives you a false return. This same question has been asked on tons of other sites in different formats. Just search Google on “PHP embedded functions” to read about it further. In my humble opinion it is badly formed code, but, it can be used in one way.

If you have some function and it creates new values to run thru another function that is okay, but, not doubled or embedded. Just makes confused code that could fail with ease do to variable parsing. (Globals vs Local variables!)

If for some reason you need to have a function call a second one, do it that way. Have a line in the first function that calls the second one. Just don’t embed them. Make sense?

I know this is really old, but I had to work thru it none the less.

So,

function x ($y) {
    function y ($z) {
        return ($z*4);
    }
    return($y+5);
}

$y = 3;
$y = x($y)*y($y);
// x(3) returns 8
// y(3) returns 12
// 8 x 12 == 96

echo $y;

That is the why. As for the how, I am not sure, because y() is not within scope and should not be accessible this way. But, the variable is plugged in before the statement executes so it comes in as,

x(3) x y(3)

because the value has not changed at the time of execution, because you are using the same variable.

Sponsor our Newsletter | Privacy Policy | Terms of Service