Voting

: max(two, two)?
(Example: nine)

The Note You're Voting On

Frederik Krautwald
18 years ago
Due to PHP 5 engine that permits to get final class in a static called function, and this is a modified version of examples published below.

<?php
abstract class Singleton {
protected static
$_instances = array();

protected function
__construct() {}

protected static function
getInstance() {
$bt = debug_backtrace();
$class = $bt[count($bt) - 1]['class'];
if (!isset(
self::$_instances[$class])) {
self::$_instances[$class] = new $class();
}
return
self::$_instances[$class];
}
}
class
A extends Singleton {
public static function
getInstance() {
return
parent::getInstance();
}
}
class
B extends Singleton {
public static function
getInstance() {
return
parent::getInstance();
}
}
class
C extends A {
public static function
getInstance() {
return
parent::getInstance();
}
}

$a = A::getInstance();
$b = B::getInstance();
$c = C::getInstance();

echo
"\$a is a " . get_class($a) . "<br />";
echo
"\$b is a " . get_class($b) . "<br />";
echo
"\$c is a " . get_class($c) . "<br />";
?>

I don't know about if performance would increase if debug_backtrace() is skipped and instead have getInstance() to accept a passed class retrieved by get_class() method as parameter as described in a post below.

By having set getInstance() to protected in the Singleton class, the function is required to be overridden (good OOP practice).

One thing to mention is, that there is no error checking in case $class is null or undefined, which would result in a fatal error. At the moment, though, I can't see how it could happen when the getInstance() is protected, i.e. has to be overridden in a subclass -- but with good coding practice you should always error check.

<< Back to user notes page

To Top