PHP StdClass - access fields as ->field or ->{'field'}

PapaFreud picture PapaFreud · Apr 18, 2011 · Viewed 8.3k times · Source

I'm working on this PHP code collaboration and it seems that some people access PHP StdClass fields like this

$body->head

and others like

$body->{'head'}

As far as I can tell these are equivalent. Are they? Does it matter which is used? Which way would you prefer? Any quirks to look out for here?

Answer

mario picture mario · Apr 18, 2011

They are equivalent. You only need the second version if you want to use abhorrent attribute names like:

$data->{'what * the ! thing'}

This sometimes happens if you convert pure data arrays into objects.

But there is also the double quotes version, which makes a bit more sense when you actually need variable attribute names (basically variable variables for objects):

$data->{"attr$index"}