note 85209 added to function.get-class
| From: | Edward at osu1 dot php dot net | Date: | Wed, 20 Aug 2008 12:42:01 +0000 |
| Subject: | note 85209 added to function.get-class | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-143678@lists.php.net to get a copy of this message | ||
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 :)
----
Server IP: 89.248.170.61
Probable Submitter: 87.211.158.196
----
Manual Page -- http://www.php.net/manual/en/function.get-class.php
Edit -- https://master.php.net/note/edit/85209
Del: integrated -- https://master.php.net/note/delete/85209/integrated
Del: useless -- https://master.php.net/note/delete/85209/useless
Del: bad code -- https://master.php.net/note/delete/85209/bad+code
Del: spam -- https://master.php.net/note/delete/85209/spam
Del: non-english -- https://master.php.net/note/delete/85209/non-english
Del: in docs -- https://master.php.net/note/delete/85209/in+docs
Del: other reasons-- https://master.php.net/note/delete/85209
Reject -- https://master.php.net/note/reject/85209
Search -- https://master.php.net/manage/user-notes.php