Only variables can be passed by reference

前端 未结 8 1221
小鲜肉
小鲜肉 2020-12-11 00:59

I had the bright idea of using a custom error handler which led me down a rabbit hole.

Following code gives (with and without custom error handler): Fatal er

相关标签:
8条回答
  • 2020-12-11 01:13

    array_pop() tries to change that value which is passed as parameter. Now in your second example this is the return value from array_slice(). In engine terms this is a "temporary value" and such a value can't be passed by references. what you need is a temporary variable:

    function foo(){
        $a=explode( '/' , 'a/b/c');
        $b=array_slice($a,-2,1);
        $c=array_pop($b);
        return $c;
    }
    print_r(foo());
    

    Then a reference to $b can be passed to array_pop(). See http://php.net/references for more details on references.

    0 讨论(0)
  • 2020-12-11 01:18

    Try this:

    function foo(){
        $a = array("a","b","c");
        $b = array_pop($a);
        return $b;
    }
    
    0 讨论(0)
  • 2020-12-11 01:19

    Same question Strict Standards: Only variables should be passed by reference, also https://bugs.php.net/bug.php?id=48937.

    0 讨论(0)
  • 2020-12-11 01:20

    I just got this error chaining methods.

    doSomething()->andThis()
    

    I had:

    doSomething()-andThis() // missing `>` character
    

    My scenario was a little more complex, but it stemmed from the accidental subtraction operation.

    0 讨论(0)
  • 2020-12-11 01:22

    It's a memory corruption issue (according to PHP dev team). Just throw in an assignment:

    function foo(){
        $b = array_pop($arr = array("a","b","c"));
        return $b;
    }
    print_r(foo());
    

    :

    function foo(){
        $a = explode( '/' , 'a/b/c');
        $c = array_pop($arr = array_slice($a,-2,1));
        return $c;
    }
    print_r(foo());
    

    The second produces an E_STRICT. You can handle that differently in your error handler if you wish (if you don't want to change those functions).

    0 讨论(0)
  • 2020-12-11 01:24

    array_pop() changes that value passed to it which is where the error is coming from. A function cannot be changed. In other words, you need to assign the array to a variable first (ref: manual), and then run array_pop().

    The code you need is this:

    function foo(){
        $a = array("a","b","c");
        $b = array_pop($a);
        return $b;
    }
    

    Edit: Both functions you mentioned have the same problem. Assign the array to a variable and pass the variable to array_pop().

    0 讨论(0)
提交回复
热议问题