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: php
-
Pingback from Asgrim » Blog Archive » PHP Base Classes on November 11, 2008 at 8:26 pm
-
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.
-
A concrete example of Janis comment.
abstract class Base
{
abstract function foo();
}class DerivedA extends Base
{
function foo() { print “In A foo()\n”; }
}class DerivedB extends Base
{
function foo() { print “In B foo()\n”; }
}function do_foo( $obj )
{
if( ! is_subclass_of( $obj, ‘Base’ ) )
{
throw new Something();
}
$obj->foo();
}
10 comments
Comments feed for this article
Trackback link: http://www.otton.org/2008/11/11/php-base-class-stdclass/trackback/