Ternary operator not working with reference variables in PHP

Why is this not working?

$a = 'FOO'; $foo = $a ? &$a : 'whatever'; // <- error here echo $foo; 

I get a parsing error: |

+2
source share
3 answers

If you want to assign a link using a triple expression, you will need this inconvenient solution:

  list($foo) = $a ? array(&$a) : array('whatever'); 

However, as stated in other answers, this rarely saves memory.

+6
source

Although you noted your question, this is not an if statement, it is a triple conditional expression. I redid it accordingly.

Now the reason it doesn't work is because assignment by reference is different from assigning expressions of normal value in PHP. You cannot use links with the ?: Operator ?: just like you cannot do return &$foo; in function. For more information, see the PHP links manual pages in these pages:

If you use the if statement, it will work:

 if ($a) $foo = &$a; else $foo = 'whatever'; 

But why would you like to use links like this outside of me (if it is not PHP 4, and even then you should no longer use PHP 4).

+6
source

Try the following:

 $a ? $foo = &$a : $foo = 'whatever'; 
0
source

Source: https://habr.com/ru/post/1386918/


All Articles