Curly Braces for Class Property Names

Nov 08, 2011

I ran into an interesting situation the other day where I was parsing an RSS into a SimpleXML object. I cannot recall the exact situation but I will replicate it below. Suppose you have an associative array with a key that that is not a valid variable name. This can happen if the key begins with a number or if the key has spaces it in. For example:

$a['1st_key'] = "first_key";
$a['k e y'] = "value";

Now lets say, for whatever reason, we cast this array to an object:

$o = (object)$a;

This will convert all the array keys into the objects properties. But, how do we access them? Both $o->k e y and $o->1st_key are obvious syntax errors. As a solution, you can use curly braces.

echo $o->{'1st_key'};
echo $o->{'k e y'};