tags:

views:

1295

answers:

6

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

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

Are simialar 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?

A: 

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
+1  A: 

I don't believe so, but what would be the benefit of accessing the items like this:

anObject.foo

instead of:

anArray['foo']
Evan Fosmark
+3  A: 

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

Gumbo
To bad it didn't make it.
Pim Jager
+7  A: 

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
Hmm nice, well i can see some situations in which this could be usable, thanks!
Sander Versluys
Yeah, in that case I might just as well use a normal associative array.
Pim Jager
A: 

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
+1  A: 

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 .
Ronald Conco