'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 1:[1]
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.
Solution 2:[2]
Changes from PHP5 to PHP7
`Expression: $foo->$bar['baz'] PHP 5: $foo->{$bar['baz']} PHP7: ($foo->$bar)['baz']`
so you have to change it like:
$baz = $this->table->{$quux['field']}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Sherif |
Solution 2 | JOUM |