Does PHP feature short hand syntax for objects?

Viewed 26222

In javascript you can easily create objects and Arrays like so:

var aObject = { foo:'bla', bar:2 };
var anArray = ['foo', 'bar', 2];

Are similar things possible in PHP?
I know that you can easily create an array using the array function, that hardly is more work then the javascript syntax, but is there a similar syntax for creating objects? Or should I just use associative arrays?

$anArray = array('foo', 'bar', 2);
$anObjectLikeAssociativeArray = array('foo'=>'bla',
                                      'bar'=>2);

So to summarize:
Does PHP have javascript like object creation or should I just use associative arrays?

7 Answers

For simple objects, you can use the associative array syntax and casting to get an object:

<?php
$obj = (object)array('foo' => 'bar');
echo $obj->foo; // yields "bar"

But looking at that you can easily see how useless it is (you would just leave it as an associative array if your structure was that simple).

There was a proposal to implement this array syntax. But it was declined.


Update    The shortened syntax for arrays has been rediscussed, accepted, and is now on the way be released with PHP 5.4.

But there still is no shorthand for objects. You will probably need to explicitly cast to object:

$obj = (object) ['foo'=>'bla', 'bar'=>2];

There is no object shorthand in PHP, but you can use Javascript's exact syntax, provided you use the json_encode and json_decode functions.

Like the json_decode idea, wrote this:

function a($json) {
 return json_decode($json, true); //turn true to false to use objets instead of associative arrays
}

//EXAMPLE
$cat = 'meow';

$array = a('{"value1":"Tester", 
  "value2":"'.$cat.'", 
  "value3":{"valueX":"Hi"}}');

print_r($array);
Related