I posted this a few days ago, inspired by David Otton’s post on this topic. A chap called Will commented about it, and after doing a quick Google, I got angry and realised how* many people are misinformed that stdClass is the base PHP class for everything.
As of the latest stable release of PHP, this is not the case. And it bugs me when people say “stdClass is the base class of everything in PHP”. stdClass is actually just a basic object with no methods or properties that you can use however you wish. A common use is to create a quick on-the-fly object, e.g.:
$obj = new stdClass(); $obj->Name = 'foobar'; $obj->Id = 24; $json = json_encode($obj);
As you can see, $obj in this context is throwaway and is just used and forgotten about. I’ll re-iterate what David Otton says about it, and is quick and simple proof:
class DoesNotExtend {}; class DoesExtend extends stdClass {}; $doesNotExtend = new DoesNotExtend(); $doesExtend = new DoesExtend(); var_dump($doesNotExtend instanceof stdClass); var_dump($doesExtend instanceof stdClass);Outputs:
bool(false)
bool(true)
So please, when someone asks “what is stdClass” etc., don’t say “Oh, it’s the base class for all objects”, because it bloody well isn’t.
* Jaxxed seems to be slightly more well-informed, but that post was back in 2005. Since then, PHP 5 has come out, and classes are implemented much better. He’s still wrong though, it’s not the base class.
November 14th, 2008 at 11:13 am
What annoyed me is that it’s a reasonable assumption that’s being undermined by language perversity. Every other modern language with a decent object system has a root superclass, after all.
I thought that was how it worked in PHP until I tried to use stdClass for type hinting.
November 14th, 2008 at 11:29 am
I agree completely – the issue of course is that PHP was never OO until PHP 5 (lets be fair, PHP 4 OO was dire). Object orientation has been hacked into PHP, and despite being quite good, it’s not a patch on fully OO languages like C++ or Java.
November 15th, 2008 at 9:48 am
It never even occurred to me that stdClass would be PHP’s root superclass! I’ve always used it in the way you did in the example – to create json objects easily. It would be nice if PHP did have a super class, as David said for things like type hinting, but I can live without that stuff. Just.
November 15th, 2008 at 10:36 am
You can sort of emulate that structure as I posted about here initially – by creating your own “superclass” and inheriting all your own custom objects from that. In the custom framework we program with at Netbasic, this is the way it works, and the code is fully object orientated. We have things like debug functions we can turn on/off easily by just changing a bool in the root object and so on, it makes life pretty easy.