note 97638 deleted from language.oop5.late-static-bindings by danbrown
| From: | danbrown@php.net | Date: | Thu, 29 Apr 2010 22:59:52 +0000 |
| Subject: | note 97638 deleted from language.oop5.late-static-bindings by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-168797@lists.php.net to get a copy of this message | ||
Note Submitter: James
----
If you're still stuck on a pre-5.3 codebase then you can fake a singleton superclass like this.
It ain't pretty, though. To do it you pass the type info down the stack manually and then
abuse call_user_func to pass the value back to the originating class so that you can access
it's static properties.
<?php
abstract class Singleton {
protected function __construct() {}
protected function __clone() {}
public function instance($class) {
$member = 'instance';
$instance = self::getStaticMember($class, $member);
if (!$instance instanceof $class) {
$instance = new $class();
self::setStaticMember($class, $member, $instance);
}
return $instance;
}
protected function setStaticMember($class, $member, $value) { call_user_func(array($class,
__FUNCTION__), $member, $value); }
protected function getStaticMember($class, $member) { return call_user_func(array($class,
__FUNCTION__), $member); }
}
class MySingleton extends Singleton {
protected static $instance = null;
public function instance() { return parent::instance(__CLASS__); }
protected function setStaticMember($member, $value) { self::$$member = $value; }
protected function getStaticMember($member) { return self::$$member; }
}
?>