Voting

: min(seven, two)?
(Example: nine)

The Note You're Voting On

Edward
16 years ago
With Late Static Bindings, available as of PHP 5.3.0, it is now possible to implement an abstract Singleton class with minimal overhead in the child classes. Late static bindings are explained here: http://nl2.php.net/manual/en/language.oop5.late-static-bindings.php

In short, it introduces a new 'static::' keyword, that is evaluated at runtime. In the following code I use it to determine the classname of the child Singleton class.

<?
abstract class Singleton {
protected static $__CLASS__ = __CLASS__;
protected static $instance;

protected function __construct() {
static::$instance = $this;
$this->init();
}

abstract protected function init();

protected function getInstance() {
$class = static::getClass();

if (static::$instance===null) {
static::$instance = new $class;
}

return static::$instance;
}

private static function getClass() {
if (static::$__CLASS__ == __CLASS__) {
die("You MUST provide a <code>protected static \$__CLASS__ = __CLASS__;</code> statement in your Singleton-class!");
}

return static::$__CLASS__;
}
}
?>

An example Singleton class can then be implemented as follows:

<?
class A extends Singleton {
protected static $__CLASS__ = __CLASS__; // Provide this in each singleton class.

protected function someFunction() {
$instance = static::getInstance();
// ...
}
}
?>

Hope this helps you save some time :)

<< Back to user notes page

To Top