PHP Notice: Array to string conversion only on PHP 7

前端 未结 2 1033
生来不讨喜
生来不讨喜 2021-01-12 01:41

I am a newbie of PHP. I study it from php.net, but I found a problem today.

class foo {
    var $bar = \'I am bar.\';
}

$foo = new foo();
$bar         


        
相关标签:
2条回答
  • 2021-01-12 02:05

    This should work with PHP 7:

    class foo {
    var $bar = 'I am bar.';
    }
    
    $foo = new foo();
    $bar = 'bar';
    $baz = array('foo', 'bar', 'baz', 'quux');
    echo "{$foo->$bar}\n";
    echo "{$foo->{$baz[1]}}\n";
    

    This is caused because in PHP 5 the following line:

    echo "{$foo->$baz[1]}\n";
    

    is interpreted as:

    echo "{$foo->{$baz[1]}}\n";
    

    While in PHP 7 it's interpreted as:

    echo "{{$foo->$baz}[1]}\n";
    

    And so in PHP 7 it's passing the entire array to $foo instead of just that element.

    0 讨论(0)
  • 2021-01-12 02:25

    Just assign array to a variable and use that variable on function call. That will work... I fixed this issue in that way.

    Because when coming to PHP 7, that will pass whole array when we directly used it on function call.

    EX:

    $fun['myfun'](); // Will not work on PHP7.
    
    $fun_name = $fun['myfun'];
    $fun_name();    // Will work on PHP7.
    
    0 讨论(0)
提交回复
热议问题