I have come across the following statement from php manual
The following things can be passed by reference:
Variables, i.e. foo($a)
New statements, i.e. foo(new foobar())
References returned from functions, i.e.
And here's an example that doesn't work:
<?php
function foo(&$var)
{
$var++;
}
function bar()
{
$a = 5;
return $a;
}
foo(bar());
I am trying to understand why it doesn't work.
bar() returns '5' by value, which foo() references, so why does PHP doesn't permit this behavior?
Is this related to this excerpt from manual:
No other expressions should be passed by reference, as the result is undefined. For example, the following examples of passing by reference are invalid
However, to me this doesn't make sense because, bar() returns an actual value, not undefined.
Only variables should be passed by reference, so this will work
function foo(&$var)
{
$var++;
}
function bar()
{
$a = 5;
return $a;
}
$a = bar();
foo($a);
var_dump($a);
There is nothing wrong... here is your example a bit more completed.
function foo(&$var)
{
$var++;
return $var;
}
function bar()
{
$a = 5;
return $a;
}
echo foo($a=bar())."
";
echo $a . "
";
It outputs the expected. 6 5 On PHP 5.6.3