note 89946 added to language.oop5.late-static-bindings
| From: | kenneth at kennethjorgensen dot com | Date: | Mon, 30 Mar 2009 10:19:00 +0000 |
| Subject: | note 89946 added to language.oop5.late-static-bindings | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-152603@lists.php.net to get a copy of this message | ||
Simple basic class which uses to get_called_class() to create singleton instances. A previous post
by php at mikebird dot co dot uk explain how to do this, but the extended static variables require
you to define them in child classes before they work.
<?php
abstract class Singleton {
private static $instances = array();
public function __construct() {
$class = get_called_class();
if (array_key_exists($class, self::$instances))
trigger_error("Tried to construct a second instance of class \"$class\"",
E_USER_WARNING);
}
public static function getInstance() {
$class = get_called_class();
if (array_key_exists($class, self::$instances) === false)
self::$instances[$class] = new $class();
return self::$instances[$class];
}
}
class A extends Singleton {
}
class B extends Singleton {
}
$a1 = A::getInstance();
$a2 = A::getInstance();
$b1 = B::getInstance();
$b2 = B::getInstance();
if (get_class($a1) == "A" &&
get_class($a2) == "A" &&
get_class($b1) == "B" &&
get_class($b2) == "B" &&
$a1 === $a2 &&
$b1 === $b2)
echo "All good\n";
else
echo "FAIL!\n";
?>
You probably noticed the use of self:: rather than static::, this is because we want the static
variable to be private, and using static:: will not allow us to do that.
----
Server IP: 87.124.35.190
Probable Submitter: 84.233.151.132
----
Manual Page -- http://www.php.net/manual/en/language.oop5.late-static-bindings.php
Edit -- https://master.php.net/note/edit/89946
Del: integrated -- https://master.php.net/note/delete/89946/integrated
Del: useless -- https://master.php.net/note/delete/89946/useless
Del: bad code -- https://master.php.net/note/delete/89946/bad+code
Del: spam -- https://master.php.net/note/delete/89946/spam
Del: non-english -- https://master.php.net/note/delete/89946/non-english
Del: in docs -- https://master.php.net/note/delete/89946/in+docs
Del: other reasons-- https://master.php.net/note/delete/89946
Reject -- https://master.php.net/note/reject/89946
Search -- https://master.php.net/manage/user-notes.php