Implementing Singleton Pattern in PHP4

October 3rd, 2006 by algis

Everyone knows how important this pattern is. Unfortunately, PHP4 lacks static class variables so the classic natural way to implement Singleton is not working here. In my applications it do this in the following way:

  1. In a global include file (you have one for sure) define a singleton helper function:
    function &mySingletonFunction( $class ) {
    	// Declare a static variable to hold the object instance
    	static $instances;
    
    	// If the instance is not there, create one
    	if( ! isset($instances[$class]) ){
    		$instances[$class] = new $class;
    		}
    	return $instances[$class];
    	}
    
  2. For every class that you would like to make Singleton, create a method:

    function &getInstance(){
    	return mySingletonFunction( 'myClassName' );
    	}
    
  3. In your main code, where you want to get a single instance of a class, you call it like this:

    $myObject =& myClassName::getInstance();
    

    So we get a fully functional Singleton pattern in PHP4 just with a couple of lines.

Posted in PHP Application Development |

Comments are closed.