note 97639 added to language.oop5.late-static-bindings
| From: | James at osu1 dot php dot net | Date: | Thu, 29 Apr 2010 22:59:08 +0000 |
| Subject: | note 97639 added to language.oop5.late-static-bindings | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-168796@lists.php.net to get a copy of this message | ||
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; }
}
?>
----
Server IP: 69.147.83.197
Probable Submitter: 195.24.233.122
----
Manual Page -- http://www.php.net/manual/en/language.oop5.late-static-bindings.php
Edit -- https://master.php.net/note/edit/97639
Del: integrated -- https://master.php.net/note/delete/97639/integrated
Del: useless -- https://master.php.net/note/delete/97639/useless
Del: bad code -- https://master.php.net/note/delete/97639/bad+code
Del: spam -- https://master.php.net/note/delete/97639/spam
Del: non-english -- https://master.php.net/note/delete/97639/non-english
Del: in docs -- https://master.php.net/note/delete/97639/in+docs
Del: other reasons-- https://master.php.net/note/delete/97639
Reject -- https://master.php.net/note/reject/97639
Search -- https://master.php.net/manage/user-notes.php