Abstract Classes in PHP: Introducing the Key Concepts - Defining a clever abstract class: preventing instantiation from non-subclasses (
Page 3 of 4 )
Since my original intention was to create a class that can’t be directly instantiated, even when called from non subclasses, I’ll build a very simple (and yet very useful) sample class, one that uses the PHP “is_subclass()” function, in order to avoid instantiation from non child classes. This new version of my sample class looks like this:
class baseClass{
function baseClass(){
if(strtolower(__CLASS__)=='baseclass'){
trigger_error('This class is abstract. It cannot be
instantiated!',E_USER_ERROR);
exit();
}
// check if non child class attempts to instantiate base
class
if(!is_subclass_of($this,'baseClass')){
trigger_error('This class is abstract. It cannot be
instantiated!',E_USER_ERROR);
exit();
}
}
}
$baseclass=&new baseClass();
Fatal error: This class is abstract. It cannot be instantiated! in path/to/file
As you can see, now the sample class introduces additional checking code, in order to avoid allowing non subclasses to instantiate the base class. To achieve this, I’ve utilized the PHP “is_subclass()” function, which comes in handy for determining whether the base class is being called from a subclass.
At this point, I’ve created a base class that can’t be directly instantiated, and additionally refuses instantiation from any non child classes. However, I’m not completely satisfied with the code utilized by the class. It uses the __CLASS__ magic constant, which sometimes can lead to unexpected results, depending on the function with which this constant is included. Thus, let’s move forward and rewrite the code of the above sample class, so it’s able to use the PHP “get_class()” function, which, as you’ll see, will result in a more robust implementation of the abstract class.