1
我尝试访问使用字符串变量具有数组形式的对象属性,但当字符串包含索引选择时无法这样做。看看这个例子..我一直在特林要做的就是用$ access3像串使用字符串访问对象的数组属性
$dummy = new stdClass();
$dummy->testNormal = 'itemNormal';
$dummy->testArray = array('item1', 'item2');
$access1 = 'testNormal';
$access2 = 'testArray';
$access3 = 'testArray[0]';
echo 'try access1: ' . $dummy->{$access1} . '<br />';
echo 'try access2: ' . $dummy->{$access2}[0] . '<br />';
echo 'try access3: ' . $dummy->{$access3} . '<br />';
echo 'try direct: ' . $dummy->testArray[0] . '<br />';
上面的代码将返回
try access1: itemNormal
try access2: item1
--- ERROR MESSAGE --
try access3: <-- does not contain anything because of error, my expectation is it will be "item1"
try direct: item1
这是不可能用PHP?
这可能与eval我认为,但你应该忘记这种方法。我很确定有更好的解决方案,比如你想要什么 – Peter
恐怕不能在一次通话中完成。一种解决方案可以是在[,并且调用$ dummy - > {<>} 之前将字符串拆分,但是您不能执行testArray [0] [1] [2] ... [n]除非你写一个函数来分割字符串并返回所需的对象元素 –