Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I assign to a variable being referenced in PHP?

Tags:

php

$bar = 7;
$foo =& $bar = 9;

From a technical stand point, wouldn't this be evaluated from right to left? So: $bar = 9; $foo =& $bar

In case anyone is wondering. The reason I'm doing this on one line is to avoid toe nail clippings.

like image 946
Sophie McCarrell Avatar asked Feb 27 '12 20:02

Sophie McCarrell


People also ask

How can you pass a variable by reference in PHP?

For passing variables by reference, it is necessary to add the ampersand ( & ) symbol before the argument of the variable. An example of such a function will look as follows: function( &$x ). The scope of the global and function variables becomes global. The reason is that they are defined by the same reference.

How do you assign the value of a one variable to another variable in PHP reference variable?

In PHP, there is a shortcut for appending a new string to the end of another string. This can be easily done with the string concatenation assignment operator ( . = ). This operator will append the value on its right to the value on its left and then reassign the result to the variable on its left.

Can we assign function to variable in PHP?

PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it.

How do you call a variable in PHP?

A variable starts with the $ sign, followed by the name of the variable. A variable name must start with a letter or the underscore character. A variable name cannot start with a number. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )


2 Answers

The assignment expression $bar = 9 doesn't return a reference to $bar (i.e. the variable itself); instead, it returns the integer value 9.

Or if you need a quote from the manual:

The value of an assignment expression is the value assigned. That is, the value of "$a = 3" is 3.

You can't assign a reference directly to a value, only to a variable that holds that value. So your handy one-liner fails spectacularly, and you'll have to split it into two.

like image 58
BoltClock Avatar answered Oct 24 '22 22:10

BoltClock


For the very same reason that

$bar =& 9; 

is not valid (because reference can point to another variable, but not constant / literal). See : http://www.php.net/manual/en/language.references.whatdo.php

like image 43
ts. Avatar answered Oct 24 '22 23:10

ts.