Search code examples
phpvariablesreferenceglobal-variablesphp-7

get attribute from class not working php 7


I have $this->table as a global variable and an object inside of it, where foo is a table field name.

example.

$this->table = t_module::__set_state(array('foo'=>"bar"))

calling another function I know that $quux['field'] contains foo, so I can get the value from the array inside $this->table.

$baz = $this->table->$quux['field']

In php 5.6 I get the correct value, 'bar'. But trying this in php 7 I get NULL as returning value. I need to get 'bar' in php 7.


Solution

  • If you read the migration guide for PHP 7 you should see that one of the Backwards incompatible changes listed there is the handling of indirect variables, properties, and methods which simply put, means that in PHP 7 everything is read from left-to-right.

    This means in the expression $baz = $this->table->$quux['field'] the expression$this->table->$quux will be evaluated first to whatever its value is and then PHP will attempt to find the key ['field'] on that expression.

    Meaning that PHP 5 reads this as

    $baz = $this->table->{$quux['field']}
    

    But PHP 7 reads it as

    $baz = ($this->table->$quux)['field']
    

    To maintain backwards compatibility you can use the braces to force the expression to be evaluated the same in both PHP 5 and PHP 7 like this...

    $baz = $this->table->{$quux['field']}
    

    Here's an example in 3v4l demonstrating it works the same in both PHP 5 and PHP 7.