The code just worked fine with PHP 5.3.
Thanks to you it could be rebuild to work with earlier versions of PHP 5.
I just changed the 'static' to 'self' and die() to an Exception.
<?php
// This one extends Singleton with proper class name
class someSingleton extends Singleton {
public static function getInstance() {
parent::$__CLASS__ = __CLASS__;
parent::getInstance();
}
}
// This one does the logic
abstract class Singleton {
protected static $__CLASS__ = __CLASS__;
protected static $instance = null;
protected function __construct() {}
abstract protected function init();
/**
* Gets an instance of this singleton. If no instance exists, a new instance is created and returned.
* If one does exist, then the existing instance is returned.
*/
public static function getInstance() {
$class = self::getClass();
if (self::$instance === null) {
self::$instance = new $class();
self::$instance->init();
}
return self::$instance;
}
/**
* Returns the classname of the child class extending this class
*
* @return string The class name
*/
private static function getClass() {
$implementing_class = self::$__CLASS__;
$original_class = __CLASS__;
if ($implementing_class === $original_class)
throw new Exception("You MUST provide a <code>protected static \$__CLASS__ = __CLASS__;</code> statement in your Singleton-class!");
return $implementing_class;
}
}
?>
--was--
The code just worked fine with PHP 5.3.
Thanks to you it could be rebuild to work with earlier versions of PHP 5.
I just changed the 'static' to 'self' and die() to an Exception.
<?php
// This one extends Singleton with proper class name
class someSingleton extends Singleton {
public static function getInstance() {
parent::$__CLASS__ = __CLASS__;
parent::getInstance();
}
}
// This one does the logic
abstract class Singleton {
protected static $__CLASS__ = __CLASS__;
protected static $instance = null;
protected function __construct() {}
abstract protected function init();
/**
* Gets an instance of this singleton. If no instance exists, a new instance is created and returned.
* If one does exist, then the existing instance is returned.
*/
public static function getInstance() {
$class = self::getClass();
if (self::$instance === null) {
self::$instance = new $class();
self::$instance->init();
}
return self::$instance;
}
/**
* Returns the classname of the child class extending this class
*
* @return string The class name
*/
private static function getClass() {
$implementing_class = self::$__CLASS__;
$original_class = __CLASS__;
if ($implementing_class === $original_class)
throw new Exception("You MUST provide a <code>protected static \$__CLASS__ = __CLASS__;</code> statement in your Singleton-class!");
return $implementing_class;
}
}
http://php.net/manual/en/function.get-class.php
lmpx.com only provides a reader for public news (NNTP) servers. It is not
affiliated with the servers or forums shown here and is not responsible for
the content of articles, which is written by their respective authors.