#native_company# #native_desc#
#native_cta#

OO Design: Abstract Classes Page 3

By Jonathan Griffin
on February 10, 2003

Implementing Abstract Classes In PHP

In order to implement an abstract class in PHP, let’s review the characteristics of an abstract
class.
  • An abstract class cannot be instantiated.
  • An abstract class can (and should) contain abstract methods (no implementation).
  • If a class contains abstract methods, it must be abstract.
  • Inherited classes must implement any inherited abstract methods, or be declared abstract as well.
Currently PHP does not support any of the above mentioned characteristics for classes. So how in
the world are we going to implement an abstract class in PHP? Simple. All we need is a little creativity
and well documented code.
First, let’s take a look at how we can prevent the instantiation of a class. For our example, we’ll declare
a class named Base, and setup an empty constructor…well, sort of.

<?php

class Base

{

  function 
Base()

  {

    
/* Do not allow instantiation of base class. */

    
if ( strcasecmpget_class($this), "Base") == ) {

      
trigger_error("Instantiation of Base prohibited."E_USER_ERROR);

      return 
NULL;

    }

  }

}

?>



Ok, so we added a few extra lines of code to the constructor. Yes, somewhat cheesy and not near as elegant
as adding an abstract modifier to the class declaration (currently not possible in PHP), but it
works. When the constructor is called, we grab the name of the class from the current instance, and compare
it to the name of class Base. If the two names match, we trigger an error halting the script.
Finished? Not quite. Although an attempt to instantiate our base class would trigger an error, nothing
prevents our constructor from being called statically, Base::Base(). Any class, regardless
of inheritance, could call our constructor through static method syntax. In fact, any code practically
anywhere could still call our constructor statically. Since PHP currently doesn’t make a distinction
between instance vs. static methods (except for $this at runtime), we just code around it.

<?php

class Base

{

  function 
Base()

  {

    
/* Do not allow instantiation of base class. */

    
if ( strcasecmpget_class($this), "Base") == ) {

      
trigger_error("Instantiation of Base prohibited."E_USER_ERROR);

      return 
NULL;

    }

    

    
/* Prevent non subclass from calling constructor. */

    
if ( !is_subclass_of($this"Base") ) {

      
trigger_error("Base constructor call not allowed."E_USER_ERROR);

      return 
NULL;

    }

  }

}

?>



1
|
2
|
3
|
4
|
5
|
6
|
7
|
8