Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 667
PapaFreud Avatar asked Apr 18 '11 08:04

PapaFreud


People also ask

How do you access the stdClass object?

Below are two examples of how to access a StdClass object one will expose the entire object, and the other will grab one property of that object. $myNameIs $data->{'name'}; Accessing the whole object called $data. The for-each loop adds it to $array, and then by using the print_r function, it will display everything.

How do you access the properties of an object in PHP?

Once you have an object, you can use the -> notation to access methods and properties of the object: $object -> propertyname $object -> methodname ([ arg, ... ] ) Methods are functions, so they can take arguments and return a value: $clan = $rasmus->family('extended');

What is stdClass object in PHP?

The stdClass is the empty class in PHP which is used to cast other types to object. It is similar to Java or Python object. The stdClass is not the base class of the objects. If an object is converted to object, it is not modified.


2 Answers

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"}
like image 197
mario Avatar answered Sep 18 '22 13:09

mario


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.

like image 39
Kamil Avatar answered Sep 19 '22 13:09

Kamil