Re: Whacky increment/assignment logic with $foo++ vs ++$foo

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Fri, Oct 2, 2009 at 2:37 PM, Ben Dunlap <bdunlap@xxxxxxxxxxxxxxxxxx> wrote:
>> My issue is that I see no reason to do the ASSIGNMENT FIRST and THEN
>> INCREMENT.
>>
>> That's just counter intuitive. In the case of $foo = $num++, everything to
>> the right of the = should be computed FIRST and THEN handed off to the left
>> side. This particular expression (and I'm unaware of any other PHP
>> expression that works this way) chooses to do some "FM" (f'n magic) and do
>> an assignment FIRST and THEN increment.
>
> It's not the expression that works that way -- it's the operator. The
> post-increment operator /always/ does its work after the expression
> that it's in has been evaluated.
>
> Are you thinking it would be more intuitive if that operator departed
> from its normal behavior in this one special case?

On further thought I do see why this one special case is a little
mind-blowing. What the heck /is/ supposed to happen when you do this:

    $a = 2;
    $a = $a++;
    echo $a;

Seems like any way you slice it the output should be 3. I guess what's
revealed here is that, as far as PHP is concerned, the $a on the right
side of the assignment expression is something like a temporary copy
of the variable in the current scope. So the assignment gets
evaluated, and then ++ operates on that "copy" and the result is
discarded.

Honestly I think the only reason anyone would write an expression like
that is either to fake out the compiler or because they don't properly
understand the use of a unary operator. Or rather, of the
increment/decrement operators, because no other unary operator
actually changes the thing it operates on (AFAIK), which makes ++ and
-- doubly weird.

Ben

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux