Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this PHP function return?

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

like image 548
Felipe Avatar asked Dec 28 '22 07:12

Felipe


2 Answers

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

like image 100
Chris Laplante Avatar answered Jan 08 '23 03:01

Chris Laplante


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.

like image 36
ontrack Avatar answered Jan 08 '23 03:01

ontrack