PHPBuilder - Non-instantiable classes in PHP4



RSS Twitter
Tips Application Architecture

Non-instantiable classes in PHP4

by: Mike Simons
|
February 9, 2004

Some classes are better left un-instantiated, but PHP4 provides no direct way to to this...

To emulate a non-instantiable class (it can be worked around if someone is hell bent on instantiating it) we have to make a constructor that will refuse an instantiation attempt...

This can simply be achieved by :

class myClass
{
  function myClass()
  {
    $this = null;
    trigger_error(
      sprintf("'%s class is un-instantiable!'", __CLASS__),
      E_USER_ERROR);
  }
}

This kills the instance during instantiation, however it will also kill any derived classes with no constructor...

Easily fixed

class myClass
{
  function myClass()
  {
    if(get_class($this)==__CLASS__)
    {
      $this = null;
      trigger_error(
        sprintf("'%s class is un-instantiable!'", __CLASS__),
        E_USER_ERROR);
    }
  }
}

Now this code will check if the current instance is the same type as the base class. If so then it kills the instance, otherwise the instantiation is allowed

Hope this is of use to someone :-)

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:
Mike Simons

Comment:



Comment:

(Maximum characters: 1200). You have characters left.