Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP object literal

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"} ] 
like image 614
Tomas Avatar asked Mar 10 '12 07:03

Tomas


People also ask

What is object literal in PHP?

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", ];

Can an object be literal?

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 is object literal type?

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.

What is object literal syntax?

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.


2 Answers

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; 
like image 181
Tim Avatar answered Oct 02 '22 07:10

Tim


As of PHP 5.4 you can also use the short array syntax:

$json = [     (object) ['name' => 'John', 'hobby' => 'hiking'],     (object) ['name' => 'Jane', 'hobby' => 'dancing'], ]; 
like image 42
mipaaa Avatar answered Oct 02 '22 08:10

mipaaa