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
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 offoo()
is put into$a
.
More information: http://en.wikipedia.org/wiki/Operator_associativity
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With