In PHP, I can specify array literals quite easily:
array( array("name" => "John", "hobby" => "hiking"), array("name" => "Jane", "hobby" => "dancing"), ... )
But what if I want array of objects? How can I specify object literal in PHP? I.e. in javascript it would be:
[ {name: "John", hobby: "hiking"}, {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", ];
In plain English, an object literal is a comma-separated list of name-value pairs inside of curly braces. Those values can be properties and functions. Here's a snippet of an object literal with one property and one function.
What are Object Literals? They are a comma-separated list of name-value pairs. Think of JSON Objects. Below is an Object Literal which contains the information for a user. An example of an Object Literal.
Declaring methods and properties using Object Literal syntax The Object literal notation is basically an array of key:value pairs, with a colon separating the keys and values, and a comma after every key:value pair, except for the last, just like a regular array.
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'], ];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With