PHP Tip: Classes Aren’t Derived From stdClass

A base class is "a class from which other classes are derived".

Many OO languages have the concept of a single base class from which all other classes are explicitly or implicitly descended. For example, Ruby, Java and .NET all have Object.

It’s a very common belief that PHP implements stdClass as a base class for all objects, but this is in fact not the case:

<?php
 
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)

Tags:

Sorry, but I am unsure of your example. By extending the stdClass and instantiating the resultant construct, a var_dump call with the object returns true, whereas without extending it, var_dump returns false… why?

@Will The point is that if you don’t explicitly extend stdClass in php it isn’t done implicitly. If you were to perform the equivalent test in Java, Ruby or .NET (as mentioned in the post) both instanceofs would yield a true, as all classes implicitly extend the base class.

Very strange that anyone would think this. The stdClass is really only used for unit testing Zend Engine bugs.

What’s even weirder is that the follow is true

Code from above comment:

php -r ‘var_dump((object)1 instanceof stdClass);’

Yet another reason that I don’t consider PHP to be truely OOP (stress on the ‘oriented’ part).

Yes, it has support for objects. Yes, it has support for PPP access, but it doesn’t have casting:

$b = new Foo();
$a = (Foo)$b;

Casting to a specific object class generates a syntax error. This completely removes the OOP tenant of “polymorphism” off the table. It also makes Interfaces a waste of time in PHP. These aren’t necessarily bad things if you consider PHP to be it’s own unique language. But if you’re going to jump on the OOP bandwagon, at least get all the way on it.

Still, in the 4 branch, objects without defined member variables equal null (but they don’t === null). I point this out because it should never have happened in a language where objects are “first class citizens”.

I won’t go into the problems with mixing static and non-static contexts.

It seems to me that if you don’t think about objects the same way that the developers of PHP do (and it doesn’t appear that they think about OOP even close to any other modern language), you are SOL.

I fail to see how lack of the explicit casting syntax makes polymorphism or interfaces a waste of time. You can still put an interface as the type hint for a method, or check if an object implements an interface and use the object like you would use the interface.

Sure, you could ignore the fact that you’re supposed to use the interface in this case, and use the object’s other methods, but that’s just you being ignorant.