获取对数组元素的引用,其中数组可作为 $obj->$propName 访问


Getting reference to array element where array is accessible as $obj->$propName

假设我们有这段代码(简化示例):

$propertyName = 'items';
$foo = new 'stdClass;
$foo->$propertyName = array(42);

此时,我想编写一个表达式,该表达式的计算结果是对数组中值的引用。

可以这样做吗?如果是这样,如何?

一个可以"完成工作"但不是我正在寻找的答案是:

// Not acceptable: two statements
$temp = &$foo->$propertyName;
$temp = &$temp[0];

但为什么要把它写成两个陈述呢?好吧,因为这行不通:

// Will not work: PHP's fantastic grammar strikes again
// This is actually equivalent to $temp = &$foo->i
$temp = &$foo->$propertyName[0];

当然&$foo->items[0]这是另一个不可接受的解决方案,因为它修复了属性名称。

如果有人想知道奇怪的要求:我在一个循环中执行此操作,其中$foo本身是对图中某个节点的引用。任何涉及$temp的解决方案都需要事后unset($temp),以便在下一次迭代中设置$temp不会完全弄乱图形;如果您对引用不非常小心,这个unset要求可能会被忽略,所以我想知道是否有办法编写此代码,从而减少引入错误的可能性。

像这样的模棱两可的表达式需要一些解析器的帮助:

$temp = &$foo->{$propertyName}[0];

顺便说一句,无论您是要查找变量别名(又名引用)还是仅查找值,这都是相同的。如果使用数组访问表示法,两者都需要它。

谷歌搜索了一下,但我找到了解决方案:

$propertyName = 'items';
$foo = new 'stdClass;
$foo->$propertyName = array(42);
$temp = &$foo->{$propertyName}[0]; // note the brackets
$temp++;
echo $temp;
print_r($foo->$propertyName);

这将打印43 array(43)

我在本文中找到了解决方案:引用 Jeff Beeman 的变量对象属性中的数组