How PHP variable variables work?

喜你入骨 提交于 2021-01-03 06:26:07

问题


I know how PHP variable variables works, but have trouble understanding why this script outputs "I am r." instead of "I am B."

<?php
class fooo {
    var $bar = 'I am bar.';
    var $arr = array('I am A.', 'I am B.', 'I am C.');
    var $r   = 'I am r.';
}
$fooo = new fooo();
$arr = 'arr';
echo $fooo->$arr[1] . "\n";
//above line output
//I am r.
?> 

回答1:


You are defining $arr = 'arr'; and then getting the second character from the string 'arr', not the array inside class Foo, that is why you are getting 'r' ([1] returning the second character from your word).

The solution? you should replace:

echo $fooo->$arr[1] . "\n";

with:

echo $fooo->arr[1] . "\n";

You should receive your desired output:

'I am B.'



回答2:


When you reference an object property, it's the name of the variable, not the variable itself. So you'll want to do:

echo $fooo->arr[1] . "\n";

To get what you expected.




回答3:


To get the 'I am B'.

You need to resolve $arr first.

echo $fooo->${$arr}[1]

The reason being is the scope of the variable which is $arr='arr' not the property $arr=array



来源:https://stackoverflow.com/questions/15536916/how-php-variable-variables-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!