Variable Variables and Arrays

Annika Backstrom
in misc, on 23 December 2008. It is tagged #Web, #PHP, and #Programming.

I'm a big fan of PHP's variable variables functionality. It's great for abstracting code with this sort of syntax:

$property_name = 'color';
echo $theClass->$property_name; // same as $theClass->color

The documentation does mention a potential tripping point with array index ambiguity. You might expect the following references to be equal:

$prop = 'internalArray';
$theClass = new stdClass;
$theClass->internalArray = array('red', 'white', 'blue');
echo $theClass->internalArray[2] == $theClass->$prop[2] ? "equal" : "not equal";

However, the above code will output "not equal" because $prop[2] is evaluated first. This returns a character index within $prop, so the final check is against $theClass->t, which is not set. Curly braces around the property can be used to clarify your meaning:

echo $theClass->internalArray[3] == $theClass->{$prop}[2] ? "equal" : "not equal";