Error message "Strict standards: Only variables should be passed by reference"

user198729 picture user198729 · Mar 1, 2010 · Viewed 160.6k times · Source
$el = array_shift($instance->find(..))

The above code somehow reports the strict standards warning, but this will not:

function get_arr(){
    return array(1, 2);
}
$el = array_shift(get_arr());

So when will it report the warning anyway?

Answer

leepowers picture leepowers · Mar 1, 2010

Consider the following code:

error_reporting(E_STRICT);
class test {
    function test_arr(&$a) {
        var_dump($a);
    }
    function get_arr() {
        return array(1, 2);
    }
}

$t = new test;
$t->test_arr($t->get_arr());

This will generate the following output:

Strict Standards: Only variables should be passed by reference in `test.php` on line 14
array(2) {
  [0]=>
  int(1)
  [1]=>
  int(2)
}

The reason? The test::get_arr() method is not a variable and under strict mode this will generate a warning. This behavior is extremely non-intuitive as the get_arr() method returns an array value.

To get around this error in strict mode, either change the signature of the method so it doesn't use a reference:

function test_arr($a) {
    var_dump($a);
}

Since you can't change the signature of array_shift you can also use an intermediate variable:

$inter = get_arr();
$el = array_shift($inter);