Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting "Only variables should be passed by reference" error?

Check out this code:

$last = end($p = explode('/', $someString));  

Getting this notice:

Only variables should be passed by reference

I'm really confused because $p is a variable.

like image 279
thelolcat Avatar asked Dec 25 '13 19:12

thelolcat


3 Answers

end() expects a variable, not a reference. In your exemple $p = explode('/', $someString) is not a variable, it's an assignment. As the documentation said:

This array is passed by reference because it is modified by the function. This means you must pass it a real variable and not a function returning an array because only actual variables may be passed by reference.

You should do this instead:

$p = explode('/', $someString);
$last = end($p); 
like image 135
Tchoupi Avatar answered Oct 02 '22 19:10

Tchoupi


The function end() expects a real variable and not a function returning an array, but if you put the function return inside double parentheses PHP does not report a strict standards notice:

$last = end( ( explode( '/', $someString ) ) );
like image 32
Danijel Avatar answered Oct 02 '22 20:10

Danijel


The problem is that you're doing assignment to a function, and the value being passed to $last is actually the result of the function, not $p. And, explode returns a reference to a variable.

Do it in two lines:

$p = explode('/', $someString);
$last = end($p);  

There's no reason to be assigning to $p inside the function call of end(), unless you're using $p later. And for stylistic clarity I'd suggest doing it in two steps anyhow.

like image 22
JAL Avatar answered Oct 02 '22 19:10

JAL