isset()当属性名称在变量中时,为什么不起作用?
$Object = new stdClass();
$Object->tst = array('one' => 1, 'two' => 2);
$tst = 'tst'; $one = 'one';
var_dump( $Object, isset( $Object->tst['one'] ), isset( $Object->$tst[ $one ] ) );
Run Code Online (Sandbox Code Playgroud)
输出以下内容:
object(stdClass)#39 (1) {
["tst"]=>
array(2) {
["one"]=>
int(1)
["two"]=>
int(2)
}
}
bool(true)
bool(false) // was expecting true here..
Run Code Online (Sandbox Code Playgroud)
编辑:继续玩弄代码,并发现了
var_dump( $Object->$tst['one'] );
Run Code Online (Sandbox Code Playgroud)
输出通知:
E_NOTICE: Undefined property: stdClass::$t
Run Code Online (Sandbox Code Playgroud)
所以我认为问题在于,在$tst[...]从对象获取属性之前,在"字符串模式"(评估字符串中的第一个字符;在本例中为"t")中评估该部分;
var_dump( $tst, $tst['one'] ); // string(3) "tst" string(1) "t"
Run Code Online (Sandbox Code Playgroud)
解决方案:是在变量name($this->{$tst})周围加上大括号,告诉解释器首先检索它的值,然后计算[...]部分:
var_dump( $Object->{$tst}['one'] ); // int(1) yay!
Run Code Online (Sandbox Code Playgroud)