Example of singleton pattern realization in PHP (since 5.3):
/**
* Singleton pattern implementation
*/
abstract class Singleton {
/**
* Collection of instances
* @var array
*/
private static $_aInstance = array();
/**
* Private constructor
*/
private function __construct(){}
/**
* Get instance of class
*/
public static function getInstance() {
// Get name of current class
$sClassName = get_called_class();
// Create new instance if necessary
if( !isset( self::$_aInstance[ $sClassName ] ) )
self::$_aInstance[ $sClassName ] = new $sClassName();
$oInstance = self::$_aInstance[ $sClassName ];
return $oInstance;
}
/**
* Private final clone method
*/
final private function __clone(){}
}
Example of usage:
class Example extends Singleton {}
$oExample1 = Example::getInstance();
$oExample2 = Example::getInstance();
echo ( is_a( $oExample1, 'Example' ) && $oExample1 === $oExample2)
? 'Same' : 'Different', "\n";
mikhail
2010-09-08 01:28:53