Mohamed Omar Mohamed Omar - 1 month ago 5
PHP Question

Why not to user return($var) if referencing the variable?

As PHP manual States


Note: You should never use parentheses around your return variable when returning by reference, as this will not work. You can only return variables by reference, not the result of a statement. If you use return ($a); then you're not returning a variable, but the result of the expression ($a) (which is, of course, the value of $a).


I can not understand why not while the coming codes will give the same result.

The code with return $var:

<?php
function a(&$a) {
$a .= "c";
return $a;
}
$b = "b";
echo a($b);
echo $b;

?>


The code with return ($var):

<?php
function a(&$a) {
$a .= "c";
return ($a);
}
$b = "b";
echo a($b);
echo $b;

?>

Answer

The examples you show are Passing by Reference, where you pass a reference of a variable to a function. The quote from the manual is about Returning References of a variable in a function.

Just like you can't pass an expression by reference, you can't return an expression by reference, and wrapping a variable in () turns it in to an expression.

Passing a Reference

function a(&$b) { $b = 1; }

$x = 0;
a($x);
echo $x; // echos 1, because a reference to $x was changed

Returning a Reference

class a {
    public $c = 0;
    public function &b() { return $this->c; }
}

$a = new a;
$x = &$a->b();
$a->c = 1;
echo $x; // echos 1, because $x is a reference to $a->c that was changed

return ( $this->c ); doesn't work and generates:

Notice: Only variable references should be returned by reference