views:

90

answers:

2

Hi.

public function add($child){
    return $this->children[]=$child;
}

Btw, this is an excerpt from PHP in Action by Dagfinn Reiersol. According to the book, this returns $child, but shouldn't it return true in case of successful assignment and false otherwise?

Thanks in advance

+9  A: 

It returns $child. This is because $child is first added to the array $this->children[]. Then, the result of this assignment is returned.

Essentially, it is shorthand for:

public function add($child){
    $this->children[]=$child;
    return $child;
}

This type of shortcut works because, in PHP, assignment is "right-associative": http://www.php.net/manual/en/language.operators.precedence.php

This means that $a = ($b = 3) is actually evaluated from right-to-left, with 3 being stored in $b and then $a. Also, here is a note on the page I provided a link to:

Although = has a lower precedence than most other operators, PHP will still allow expressions similar to the following: if (!$a = foo()), in which case the return value of foo() is put into $a.

More information: http://en.wikipedia.org/wiki/Operator_associativity

SimpleCoder
Hm.. Ok.. I haven't much time right now but I'll give it a little more thought and then come back and mark it as the right answer. Thanks.
Felipe Almeida
Ok thanks, I posted what the expression would look like without using the shortcut.
SimpleCoder
Nice explanation, @SimpleCoder. But yikes -- the length of explanation required is a perfect illustration of why that sort of shorthand is a BAD IDEA in real-life code. Hope the author of PHP in Action was using it as a case-study of how not to write maintainable code.
Ben Dunlap
@Ben Dunlap; Thanks. I 100% agree, it is VERY easy to mistake `=` for `==` in those situations. That's how nasty errors and mistakes creep in.
SimpleCoder
+1  A: 

It does return child, because an assignment just returns whatever was assigned.

Whether or not it should return true on success is not a rule, so if it was documented to return child, it is correct.

ontrack