PHP object literal

TMS picture TMS · Mar 10, 2012 · Viewed 30.8k times · Source

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"}
]

Answer

Tim picture Tim · Mar 10, 2012

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;