why is the ++ operator in php working on an object property?
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?
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.
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.
精彩评论