Friday 2 October 2015

PHP: a quick question about creating generic objects

G'day:
I Twittered this yesterday, but I got no response. Here's a quick PHP question. I need to group some properties together in a throwaway object. It would be overkill to create a class for it, and I don't like the idea of using arrays to collect key/value pair data together (even though this is a ubiquitous practice in PHP... it just seems wrong to me).

So I have two options:

$mySimpleObj = (object)['foo'=>'bar'];

or:

$mySimpleObj = new stdClass();
$mySimpleObj->foo = 'bar';

I like using literals where I can, so I erred towards the former. Plus it's nicely only one statement. However after discussion with the guys here who actually know PHP, they felt happier with the latter. I changed my code.

Doing some reading, the impression I get is stdClass (nce nm, btw, PHP. ? t/ nd to use t/ abbrev thre?) is something that exists to facilitate stuff like JSON deserialisation or other functionality which needs to create an object, but not of a specific type. I'm not so sure the intent is to actually explicitly create stdClass objects? But I dunno, and I only googled for a few minutes.

Anyway, what do you think? I'm interested to hear if people have a well-formed opinion either way, or whether it's "yeah, it doesn't really matter".

Cheers.

--
Adam

BTW: that was "nice name, by the way, PHP. Why the need to use the abbreviation there?"