Tierra Innovation

Tierra Lab

PHP Tip: Inline StdClass Object Creation

One of my pet peeves is that PHP does not have syntax to support inline StdClass object creation.  Something like this would be great:

$foo = {“bar”: “baz”, “bam”: “boom”};

so you end up doing something like this:

$foo = new StdClass;
$foo->bar = “baz”;
$foo->bam = “boom”;

but you don’t have to.  Using PHP’s casting operator you can create the object in one line:

$foo = (object) array(“bar” => “baz”, “bam” => “boom”);

Which I think looks a lot cleaner.

Bookmark and Share

6 Responses to “PHP Tip: Inline StdClass Object Creation”

  1. Frank Says:

    sweet tip thanks!

  2. Balh Says:

    Used to think objects where cooler than arrays too, but what usually your best best is to just use an array, then you have the nice sorting, mapping, etc. The type conversion to object is also not free.

  3. Doug Says:

    I use stdclass objects mostly when I need to serialize them in json to the page to use in javascript. I also think the syntax looks a little cleaner.

  4. Scotty Delicious Says:

    @Doug: json_encode() works perfectly on associative arrays.

    +1 to Balh on the point about mapping and sorting. That is a lot of free function you have to give up for object syntax. I guess as a developer you really have decide if there is a strong benefit from producing an object rather than an array.

  5. Robert Lee Says:

    Also, PHP internally stores both object and arrays as hash-tables, so by storing in an object, you don’t save any memory for storage like you would in (for example) Java (Java pojo’s or even beans are far more memory efficient than HashMap’s — this is not true in PHP).

  6. joe Says:

    I’m new to php. I’ve inherited a codeigniter project, and I was about to scour the web for a solution and yours was at the top of the list! Fantastic tip Thanks!


Leave a Reply

Copyright © 2010 Tierra Innovation, Inc.