Strict Standards: Only variables should be passed by reference


Question

$el = array_shift($instance->find(..))

The above code somehow reports the strict standars 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?

1
81
6/26/2014 7:39:05 PM

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);
93
12/11/2018 9:57:36 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon