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.

const x = {
  a: "test",
  b: "test2",
  c: "test3",
};

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.

$x = (object) [
    'test',
    'test2',
    'test3',
];
var_dump($x);

/*
object(stdClass)#1 (3) {
  [0]=>
  string(4) "test"
  [1]=>
  string(5) "test2"
  [2]=>
  string(5) "test3"
}
*/

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.

$x = (object) [
    'a' => 'test',
    'b' => 'test2',
    'c' => 'test3'
];
var_dump($x);

/*
object(stdClass)#1 (3) {
  ["a"]=>
  string(4) "test"
  ["b"]=>
  string(5) "test2"
  ["c"]=>
  string(5) "test3"
}
*/

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.

$x = (object) [
    'a' => 'test',
    'b' => 'test2',
    'c' => 'test3',
    'a' => 'wipeout'
];
var_dump($x);

/*
object(stdClass)#1 (3) {
  ["a"]=>
  string(7) "wipeout"
  ["b"]=>
  string(5) "test2"
  ["c"]=>
  string(5) "test3"
}
*/

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.