문제

Suppose that we have this code (simplified example):

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

At this point I 'd like to write an expression that evaluates to a reference to the value inside the array.

Is it possible to do this? If so, how?

An answer that will "do the job" but is not what I 'm looking for is this:

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

But why write it as two statements? Well, because this will not work:

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

Of course &$foo->items[0] is another unacceptable solution because it fixes the property name.

In case anyone is wondering about the strange requirements: I 'm doing this inside a loop where $foo itself is a reference to some node inside a graph. Any solution involving $temp would require an unset($temp) afterwards so that setting $temp on the next iteration does not completely mess up the graph; this unset requirement can be overlooked if you are not ultra careful around references, so I was wondering if there is a way to write this code such that there are less possibilities to introduce a bug.

도움이 되었습니까?

해결책

Ambiguous expressions like that need some help for the parser:

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

Btw, this is the same regardless if you're looking for the variable alias (a.k.a. reference) or just the value. Both need it if you use the array-access notation.

다른 팁

It took some googling, but I found the solution:

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

$temp = &$foo->{$propertyName}[0]; // note the brackets

$temp++;

echo $temp;
print_r($foo->$propertyName);

This will print 43 array(43).

I found the solution in this article: Referencing an array in a variable object property by Jeff Beeman

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top