0

recently I did a test on return reference function follow the official example here , but confused with the result when return '++$a' instead, it seems they should be same from the answer What's the difference between ++$i and $i++ in PHP? It seems related to the version of PHP.

php version

PHP 5.6.28 (cli) (built: Dec  6 2016 12:38:54)
Copyright (c) 1997-2016 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2016 Zend Technologies

code

function &fun(){
        static $var = 1;
        return ++$var;
}

function &bar() {
    static $var = 1;
    ++$var;
    return $var;
}

$var2 =& fun();
$var3 =& bar();
fun();
bar();

echo 'var2:', $var2; // 2  why is it 2 instead of 3?
echo 'var3:', $var3; // 3
Community
  • 1
  • 1
Richard Li
  • 49
  • 4

2 Answers2

0

You are using a reference to the same variable. So when you run bar() your $var is already 2.

Pradeep
  • 9,667
  • 13
  • 27
  • 34
Sergei Kutanov
  • 825
  • 6
  • 13
-1
function &fun(){
        static $var = 1;
        return ++$var;
}

this function makes very little sense, because its return expression contains a value as the operand. The value is being returned after evaluating the unary prefix operator ++.

So, ++$var increments a variable, then returns a value of the variable, not a reference to a variable itself.

In short: references can be only obtained for a variables, taking a reference from a value does not make much sense.

zerkms
  • 249,484
  • 69
  • 436
  • 539
  • from php manual [Incrementing/Decrementing Operators](http://php.net/manual/en/language.operators.increment.php), `++$a, Increments $a by one, then returns $a.` why do you say that returns a _value_ of the variable. – Richard Li Mar 21 '17 at 03:19
  • @RichardLi because in php expressions returns values. File a bug so that they clarified that in the documentation, it clearly must be improved to avoid misunderstanding. – zerkms Mar 21 '17 at 08:22