Search code examples
phparraysreferencevariable-variables

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


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.


Solution

  • 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.