#native_company# #native_desc#
#native_cta#

OO Design: Abstract Classes Page 4

By Jonathan Griffin
on February 10, 2003

We now have an abstract base class that cannot be instantiated or have the constructor called directly,
unless from a subclass. Attempting either of the following calls would result in a script error.

<?php

$base 
= new Base();

Base::Base();

?>



To finalize this example, let’s clean up our code a little. The second if() statement can
actually serve two purposes. It solves our need to prevent the constructor from being called statically.
It indirectly solves the instantiation of the class as well. To see for your self, comment out the first
if() statement, and once more attempt to instantiate the class or call the constructor
statically. You should still get a script error. All that’s left is to modify our error message a bit.
The final code provides a simple way to prevent class instantiation and simulate an abstract class.

<?php

class Base

{

  function 
Base()

  {

    
/*

     * Do not allow instantiation of base class.

     * Prevent non subclass from calling constructor.

     */

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

      
trigger_error("Base instantiation from non subclass."E_USER_ERROR);

      return 
NULL;

    }

  }

}

?>



For the remaining characteristics of an abstract class, we will provide well-written comments in our code.
Most of the remaining characteristics (i.e. inherited classes must implement inherited abstract methods)
are forced at compile time by languages such as Java. You can use the method_exists() function
to ensure a subclass has the methods of the base. Of course, this will always return true, since the
methods do exist through inheritance. A distinction between abstract and non-abstract methods doesn’t exist
in PHP. There is no sensible way to check for implementation (if anyone knows otherwise, please share your
knowledge). Therefore you must provide appropriate comments informing the implementer what is expected.

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