A very short and simple trick for creating new stdClass objects without having to set every property individually. This is akin to JavaScript’s object notation, but not quite as elegant.

Creating a new object in JavaScript looks like the following example.

With PHP it is possible to use type casting to convert a simple array into a stdClass object which gives you a similar looking syntax although there is a little more typing required.

Note the type casting with (object) just before the array definition - this is what does the work of converting the simple array definition into a stdClass object.

Of course you’re going to want named properties too and handily casting an associative array does just that.

What happens if you have two array indexes with the same key though? Obviously you cannot have two class properties with the same name so one would presume an error. Well being that this is PHP you may not be surprised to see the following.

There is no great big crash. PHP simply overwrites the property value ($x->a in this case) with the last value of key a in the array. This is why $x->a is set to wipeout and not test.

Also note here that the order of the properties in the stdClass might not be what you were expecting either. Perhaps you were expecting $x->a to be last, but no $x->a comes first because 'a' => 'test' is set against the stdClass and it is then overwritten (rather than replaced) by the later definition 'a' => 'wipeout'.

Well there you have it - a very simple way of getting yourself a new stdClass with your desired properties set.