PHP write objects inline
arrays, javascript, object, php, syntax
Solution
Starting from PHP 5.4 short array syntax has become available. This allows you to initialize array like this:
$myArray = ["propertyA" => 1, "propertyB" => 2];
There is no currently short object syntax in PHP as of PHP 8.2. But you can cast short array syntax to create objects like this:
$object = (object) [
'this' => 'that',
'foo' => (object) [
'bar' => 123
]
];
Looks much nicer and shorter than using the following construct:
$object = new \StdClass();
$object->this = 'that';
$object->foo = \StdClass();
$object->foo->bar = 123;
Problem
Im starting to move away from using arrays in PHP as objects are so much neater and in php 5 there is no performance hits when using objects. Currently the way I do it is: `$object = (object) array('this' => 'that', 'foo' => (object) array('bar' => 123));` However, i find it so tedious to have to typecast every time as typecasting isnt recursive... Is there any way in php (or will there be) to do it like this or something similar: ``` $object = { 'this' => 'that', 'foo' => { 'bar' => 123 } }; ```