Use type casting for create stdClass objects in PHP. Its convert simple array into a stdClass object. This is very quick and easy way to creating new stdClass objects with desired properties set.
Example to Create stdClass Objects in PHP
You must declare type cast objects before the array definition. check below PHP example to create stdClass object:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?php $x = (object) [ 'one', 'two', 'three', ]; echo "<pre>"; print_r($x); ?> /* Output: stdClass Object ( [0] => one [1] => two [2] => three ) */ |
If you need to create stdClass object for associative array the use this code example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
$x = (object) [ 'x' => 'one', 'y' => 'two', 'z' => 'three' ]; echo "<pre>"; print_r($x); /* Output: stdClass Object ( [x] => one [y] => two [z] => three ) */ |
Another case if you are going to use two array indexes with same key. Of course this is not allow to do, but what PHP do, Its just overwrites the property value the last key value in the array. Check the case below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?php $x = (object) [ 'x' => 'one', 'y' => 'two', 'z' => 'three', 'x' => 'four' ]; echo "<pre>"; print_r($x); ?> /* Output: stdClass Object ( [x] => four [y] => two [z] => three ) */ |
See ‘x’ key value overwrite with the last same key value. So this happen when you trying to use two array indexes with same key.
Here it is, quick and easy way to create stdclass object with desired properties value. Use this and share with others, Thanks