PHP object literal
As BoltClock mentioned there is no object literal in PHP however you can do this by simply type casting the arrays to objects:
$testArray = array(
(object)array("name" => "John", "hobby" => "hiking"),
(object)array("name" => "Jane", "hobby" => "dancing")
);
echo "Person 1 Name: ".$testArray[0]->name;
echo "Person 2 Hobby: ".$testArray[1]->hobby;
As of PHP 5.4 you can also use the short array syntax:
$json = [
(object) ['name' => 'John', 'hobby' => 'hiking'],
(object) ['name' => 'Jane', 'hobby' => 'dancing'],
];
As others have noted, there is no object literal in PHP, but you can "fake" it by casting an array to an object.
With PHP 5.4, this is even more concise, because arrays can be declared with square brackets. For example:
$obj = (object)[
"foo" => "bar",
"bar" => "foo",
];
This would give you an object with "foo" and "bar" properties. However, I don't think this really provides much advantage over using associative arrays. It's just a syntax difference.
Consider embracing the uniqueness and "flavor" of all the languages you use. In JavaScript, object literals are all over the place. In PHP, associative arrays are functionally the same as JavaScript object literals, are easy to create, and are well understood by other PHP programmers. I think you're better off embracing this "flavor" than trying to make it feel like JavaScript's object literal syntax.
Another way would be to use the __set_state()
magic method:
$object = stdClass::__set_state (array (
'height' => -10924,
'color' => 'purple',
'happy' => false,
'video-yt' => 'AgcnU74Ld8Q'
));
Some more on the __set_state() method, where is it coming from and how is it supposed to be used.
Although casting as an (object) works fine on a single hierarchical level, it doesn't go deep. In other words, if we want objects at every level, we'd have to do something like:
$foods = (object)[
"fruits" => (object)["apple" => 1, "banana" => 2, "cherry" => 3],
"vegetables" => (object)["asparagus" => 4, "broccoli" => 5, "carrot" => 6]
];
However, instead of doing multiple casting as objects, we can wrap the whole thing in a json_encode and json_decode like this:
$foods = json_decode(json_encode([
"fruits" => ["apple" => 1, "banana" => 2, "cherry" => 3],
"vegetables" => ["asparagus" => 4, "broccoli" => 5, "carrot" => 6]
]));
That makes sure it's an object at the deepest level.
To answer klewis, you can then access this like:
echo $foods->vegetables->broccoli;
This example would output the number 5.