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

2

14

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?

Crystallite answered 18/4, 2011 at 8:17 Comment(0)
C
21

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"}
Chare answered 18/4, 2011 at 8:22 Comment(1)
Yep. Just avoid $body->{'head'} if possible.Hypnotist
K
2

I need to create class with abnormal property names like this {'field-name'}.

class myclass
{
    public {'field-name-with-minus-sign'} = "something";
}

Id doesnt work. Why? I dont want to use something like this:

$myclass = new stdClass();
$myclass->{'dumb-property-name'}

because i have a lot of properties like this.

Kassa answered 17/2, 2012 at 2:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.