0

Here is my code:

$page = explode("/", Request::url());
$page = end($page);

As you know, $page contains the last argument of the URL. Code above works as well and all fine.

But when I write it like this:

$page = end(explode("/", Request::url()));

Then surprisingly it throws this error:

Only variables should be passed by reference

Why?

stack
  • 10,280
  • 19
  • 65
  • 117
  • 1
    http://stackoverflow.com/questions/4636166/only-variables-should-be-passed-by-reference – Faradox Oct 16 '16 at 08:23
  • 1
    The array parameter of the end function 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. – Cristofor Oct 16 '16 at 08:23
  • http://php.net/manual/en/function.end.php – Cristofor Oct 16 '16 at 08:24

2 Answers2

1

explode(...) is evaluated, creating a an instance that in the first example is owned by your variable $page. Then you pass that instance by reference to end(...), end everything is fine.

In the second case, it is not owned at all, just created, then not held by any variable, so the temporary instance is immediately deallocated, and only then passed to end(...).

yeoman
  • 1,671
  • 12
  • 15
0

It's not that surprising. When a value is passed by reference, it means that the function can alter the variable and the changes will be visible outside the function. Take this code:

$byValue = 5;

function passByValue($variable)
{
    $variable++;
    echo 'Value inside ' . $variable . PHP_EOL;
}

passByValue($byValue);
echo 'Value outside ' . $byValue . PHP_EOL;


$byReference = 10;

function passByReference(&$variable)
{
    $variable++;
    echo 'Value inside ' . $variable . PHP_EOL;
}

passByReference($byReference);
echo 'Value outside ' . $byReference . PHP_EOL;

What it means is that the passByReference function needs to have access to the memory location where the variable is stored in order to change it and for that memory location to exist, you need to have a variable pointing to it. However the result of a function is "volatile" in that fashion, it will get garbage collected if it's not stored in a variable, thus cannot be passed by reference.

The end(), next() and so on function need parameters to be passed by reference to alter their internal states.

motanelu
  • 3,945
  • 1
  • 14
  • 21