从 php 5.4 到 php 7 ,使用动态变量很困惑

from php 5.4 to php 7 , useing dynamic variables is confused

我的 php 从 php 5.4 更新到 php 7.0.33 ,但是 php 代码因动态变量

而出错

php 5.4 一些这样的代码...

$attributes=array('boy','girl','none' );
$this->boy = 'eric';
$this->girl = 'lili';
$this->none = 'who';
            
echo $attributes[0];                    //=>php 5 is "boy"  | php 7 is "boy"
print_r( $this->$attributes[0] );       //=>php 5 is "eric" | php 7 is empty
print_r( $this->${attributes}[0] );     //=>php 5 is "eric" | php 7 is empty

当我在php 7 shome code 中使用时,shome 代码变空了,我该如何解决这个问题

我已经看了推荐页 Using braces with dynamic variable names in PHP ,但还是很困惑

对于这样的动态变量,您需要将字符串用大括号括起来。你几乎在最后一行就把它放在那里了。但是,请记住,您用来指示动态变量的不是数组 $attributes,而是位于 $attributes[0].

的字符串

所以这应该有效:

$this->{$attributes[0]}

动态变量名很强大,但容易混淆。如果您可以选择,我建议您只使用一个数组:

$this->attributes = [
    "boy"  => "eric",
    "girl" => "lili",
    "none" => "who"
];

echo $this->attributes["boy"];

您要搜索的语法是

 print_r( $this->{$attributes[0]} );