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.
Leave a Reply
Copyright © 2010 Tierra Innovation, Inc.
|
RSS | Client Login
June 26th, 2009 at 10:37 am
sweet tip thanks!
June 26th, 2009 at 10:50 am
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.
June 26th, 2009 at 11:25 am
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.
June 26th, 2009 at 6:01 pm
@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.
August 3rd, 2009 at 7:22 pm
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).
November 28th, 2009 at 8:55 pm
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!