tags:

views:

85

answers:

3

I showed this code to my friend

$user->attempts++; // the attempts property returns an int

and he was like saying how stupid that code was, rambling that numeric operators will produce syntax errors when attached to objects; the thing is it worked as I expected it to (increment attempts by 1, oh yeah, I tested it)

and so I ask, why the hell is this working?

+4  A: 

It works because it makes sense. $user->attempts is a integer. Forget that it's attached to an object; it's an integer. If ++ didn't work, I'd be surprised.

However, I often find that PHP syntax doesn't work as I expect, and that it's fixed in a future version. It's the sort of thing where one would typically expect it to work but, given personal experience with PHP, may have lowered one's expectations. Perhaps this is what your friend is feeling.

Matchu
Downvote for unnecesary php bashing and incorrectness.
Mike Sherov
Oh, I use PHP often. I'm working with it now, and it's where I got my start. I've just personally experienced broken syntax more often than I would have liked.
Matchu
The answer is a good answer, no real need for a down vote aside from language envy :P
Craig
I understand that sometimes PHP syntax is a little ambiguous since it can look like something from another language but act a little differently, but... postfix? I don't think any future versions are going to change how the `++` operator works. The PHP community isn't that batty.
Andrew Noyes
Ok, fine downvote removed
Mike Sherov
As someone who discovered a memory corruption bug in: "$temp = 0;" I agree with @Matchu +1 (This bug was fixed about a year ago)
TheJacobTaylor
Jacob, you have a link to the bug report? I'm curious.
Mike Sherov
+14  A: 

Because your friend is wrong

Mike Sherov
Obvious is obvious.
poke
+2  A: 

Because it's a variable inside the class that $user points to.

class User {
    public $attempts = 0;
}

$user = new User;
$user->attempts++; // works.

It's the same thing with arrays, it doesn't matter where the variable is:

$foo = array('bar' => array('baz' => 0));
$foo['bar']['baz']++; // works.
Tatu Ulmanen