44

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?

AbsoluteƵERØ
  • 7,816
  • 2
  • 24
  • 35
Pim Jager
  • 31,965
  • 17
  • 72
  • 98
  • Not that I'm aware.. And why would you want to? Javascript is so limited in comparison? Objects should be described properly, and with scope and hinting, etc. – DreamWerx Jan 18 '09 at 20:11
  • 1
    any chance you can change the accepted answer on this one? the answer to this question has changed in the last 6 years. :) – Kip Jul 18 '15 at 21:01
  • *shorthand is always one word though. – GeneC May 13 '21 at 03:19
  • I came here looking for "PHPON" (PHP object notation), which would be a PHP equivalent of JSON, and which I would find handy. Apparently it doesn't exist. Anyway, I found that using `var_export($var)` returns what I needed, even if it's not the most compact form. So this may be off-topic, sorry, but in case it's useful to someone... I'm leaving this comment. Feel free to tell me or downgrade me or ask me to delete this if it's a bad comment. – Kai Carver Nov 24 '22 at 15:21
  • Does this answer your question? [PHP object literal](https://stackoverflow.com/questions/9644870/php-object-literal) – apaderno Apr 02 '23 at 18:29

7 Answers7

58

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).

Crescent Fresh
  • 115,249
  • 25
  • 154
  • 140
  • Hmm nice, well i can see some situations in which this could be usable, thanks! – Sander Versluys Jan 18 '09 at 20:34
  • Yeah, in that case I might just as well use a normal associative array. – Pim Jager Jan 18 '09 at 22:27
  • 10
    `$goose->foo` is much prettier than `$goose['foo']`. ∴ useful. – RyanM Sep 25 '12 at 05:05
  • working with objects is easier because if you have an intricate structure of objects and arrays and maps you can go from something like this `$group["id123abc"]["people"][0]["name"]` to this `$group["id123abc"]->people[0]->name`. This makes it easier to grasp the difference between an array, a map and an object or structure – santiago arizti Jul 29 '19 at 20:23
45

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];
salathe
  • 51,324
  • 12
  • 104
  • 132
Gumbo
  • 643,351
  • 109
  • 780
  • 844
  • 6
    This has been implemented in PHP 5.4. – Tatu Ulmanen Oct 13 '11 at 11:20
  • 2
    @Gumbo the short array syntax uses `=>` not `:`. Edited the answer for you. :) – salathe Oct 13 '11 at 11:54
  • 4
    I wonder if a shorthand notation for objects will ever be implemented? I use stdClasses all the time, but they feel so awkward compared to javascript object literals. – Mahn Aug 22 '12 at 13:00
  • This method doesn't work in class variable declaration. For example `protected $test = (object) ['prop'=>'val'];` doesn't work. – Andy Fleming Feb 09 '14 at 09:52
  • Yep, this method now works, but still it sure would be nice to have `$obj = {'foo'=>'bla'}` – Phil Tune Dec 21 '17 at 19:34
  • There's an [inactive RFC from 2011](https://wiki.php.net/rfc/objectarrayliterals) for the shorthand object syntax. – bit2shift Dec 24 '17 at 12:41
11

As of PHP 5.4, you can do this:

$array = ['foo'=>'bla', 'bar'=>2];

It's not much shorter, but you'll appreciate it if you need to use a lot of hard coded nested arrays (which isn't altogether uncommon).

If you want an object, you would still need to cast each array:

$object = (object) ['foo'=>'bla', 'bar'=>2];
Matthew
  • 47,584
  • 11
  • 86
  • 98
10

According to the new PHP syntaxes,

You can use

$array = [1,2,3];

And for associative arrays

$array = ['name'=>'Sanket','age'=>22];

For objects you can typecast the array to object

$object = (object)['name'=>'Sanket','age'=>22];
Sanket Sahu
  • 8,468
  • 10
  • 51
  • 65
2

The method provided by crescentfresh works very well but I had a problem appending more properties to the object. to get around this problem I implemented the spl ArrayObject.

class ObjectParameter extends ArrayObject  {
     public function  __set($name,  $value) {
        $this->$name = $value;
    }

    public function  __get($name) {
      return $this[$name];
    }
}

//creating a new Array object
$objParam = new ObjectParameter;
//adding properties
$objParam->strName = "foo";
//print name
printf($objParam->strName);
//add another property
$objParam->strUser = "bar";

There is a lot you can do with this approach to make it easy for you to create objects even from arrays, hope this helps .

Davide Gualano
  • 12,813
  • 9
  • 44
  • 65
Ronald Conco
  • 855
  • 7
  • 11
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.

Justin Poliey
  • 16,289
  • 7
  • 37
  • 48
  • Interesting idea, though doesn't that delay parsing until run-time? When would this have an advantage over casting an array with `(object)`? – ToolmakerSteve Mar 06 '19 at 23:11
1

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);