从 class 获取属性无效 php 7
get attribute from class not working php 7
我有 $this->table
作为全局变量和其中的对象,其中 foo 是 table 字段名称。
示例。
$this->table = t_module::__set_state(array('foo'=>"bar"))
调用另一个函数我知道$quux['field']
包含foo
,所以我可以从$this->table
.
中的数组中获取值
$baz = $this->table->$quux['field']
在 php 5.6 中我得到了正确的值,'bar'
。但是在 php 7 中尝试这个我得到 NULL 作为返回值。我需要在 php 7.
中得到 'bar'
如果你阅读 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 简单地说,意味着在 PHP 7 中所有内容都是从 从左到右 .
这意味着在表达式 $baz = $this->table->$quux['field']
中,表达式 $this->table->$quux
将被计算 first 到它的值,然后 then PHP 将尝试在 that 表达式上找到键 ['field']
。
意味着 PHP 5 读作
$baz = $this->table->{$quux['field']}
但是PHP7读作
$baz = ($this->table->$quux)['field']
为了保持向后兼容性,您可以使用大括号强制在 PHP 5 和 PHP 7 中对表达式进行相同的计算,如下所示...
$baz = $this->table->{$quux['field']}
这是一个 example in 3v4l 证明它在 PHP 5 和 PHP 7 中工作相同。
从 PHP5 更改为 PHP7
`Expression: $foo->$bar['baz'] PHP 5: $foo->{$bar['baz']} PHP7: ($foo->$bar)['baz']`
所以你必须像这样改变它:
$baz = $this->table->{$quux['field']}
我有 $this->table
作为全局变量和其中的对象,其中 foo 是 table 字段名称。
示例。
$this->table = t_module::__set_state(array('foo'=>"bar"))
调用另一个函数我知道$quux['field']
包含foo
,所以我可以从$this->table
.
$baz = $this->table->$quux['field']
在 php 5.6 中我得到了正确的值,'bar'
。但是在 php 7 中尝试这个我得到 NULL 作为返回值。我需要在 php 7.
'bar'
如果你阅读 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 简单地说,意味着在 PHP 7 中所有内容都是从 从左到右 .
这意味着在表达式 $baz = $this->table->$quux['field']
中,表达式 $this->table->$quux
将被计算 first 到它的值,然后 then PHP 将尝试在 that 表达式上找到键 ['field']
。
意味着 PHP 5 读作
$baz = $this->table->{$quux['field']}
但是PHP7读作
$baz = ($this->table->$quux)['field']
为了保持向后兼容性,您可以使用大括号强制在 PHP 5 和 PHP 7 中对表达式进行相同的计算,如下所示...
$baz = $this->table->{$quux['field']}
这是一个 example in 3v4l 证明它在 PHP 5 和 PHP 7 中工作相同。
从 PHP5 更改为 PHP7
`Expression: $foo->$bar['baz'] PHP 5: $foo->{$bar['baz']} PHP7: ($foo->$bar)['baz']`
所以你必须像这样改变它:
$baz = $this->table->{$quux['field']}