Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does PHP feature short hand syntax for objects?

Tags:

object

php

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?

like image 317
Pim Jager Avatar asked Jan 18 '09 20:01

Pim Jager


People also ask

What is PHP object syntax?

In PHP, Object is a compound data type (along with arrays). Values of more than one types can be stored together in a single variable. Object is an instance of either a built-in or user defined class. In addition to properties, class defines functionality associated with data.

How do I declare an object in PHP?

To create an Object in PHP, use the new operator to instantiate a class. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created.

How do you declare an array of objects in PHP?

PHP allocates memory dynamically and what's more, it doesn't care what sort of object you store in your array. If you want to declare your array before you use it something along these lines would work: var $myArray = array(); Then you can store any object you like in your variable $myArray.

Is PHP an object or array?

Definition and UsageThe is_array() function checks whether a variable is an array or not. This function returns true (1) if the variable is an array, otherwise it returns false/nothing.


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

like image 133
Crescent Fresh Avatar answered Sep 24 '22 10:09

Crescent Fresh


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]; 
like image 33
Gumbo Avatar answered Sep 23 '22 10:09

Gumbo