One of PHP’s major OO flaws

Today I tried to use type hinting for one of my methods. I wanted to hint that one should provide an arbitrary object. This sounds very straightforward, if you familiar with Java. But in PHP it seems this is not as straightforward as you might expect. At first I made the method declaration like this: public function test(Object $object). But this the PHP parser complained that it could not find the class Object. So I tried class, but this is a reserved word. Same for default.

So I started an investigation via Google, but I couldn’t find anything useful. So I made this code and executed it:

<?php
class Test{
public function __construct() {
echo 'Class: ' . __CLASS__ . "\n";
echo 'Parent?: ' . get_parent_class(__CLASS__) . "\n";
echo 'Parent?: ' . get_class(parent) . "\n";
}
}new Test();
?>

This was the result:

Class: Test
Parent?:
Parent?:

A standard class seems to extend noting…

In conclusion, it seems PHP has no main class that is extended by default. As a result you cannot request for a generic object via type hinting. The only work around seems to call this at the beginning of your method: assert( is_object($object)  );...

Tags: , , , ,

Leave a Reply