ConFoo Montreal 2026: Call for Papers

Voting

: max(five, six)?
(Example: nine)

The Note You're Voting On

kenneth at kennethjorgensen dot com
16 years ago
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.

<< Back to user notes page

To Top