Skip to content

Instantly share code, notes, and snippets.

@syavorsky
Created June 11, 2012 07:54
Show Gist options
  • Save syavorsky/2908981 to your computer and use it in GitHub Desktop.
Save syavorsky/2908981 to your computer and use it in GitHub Desktop.
PHP Singleton with child classes
<?php
abstract class ParentClass {
private static $instances = array();
function getInstance($obj) {
$class = get_called_class();
if (!array_key_exists($class, self::$instances)) {
self::$instances[$class] = new SplObjectStorage;
}
if (!self::$instances[$class]->contains($obj)) {
self::$instances[$class]->attach($obj, new $class($obj));
}
return self::$instances[$class]->offsetGet($obj);
}
}
class ChildClass1 extends ParentClass {}
class ChildClass2 extends ParentClass {}
$obj = new stdClass;
$inst1 = ChildClass1::getInstance($obj);
printf("I am %s, my class is %s\n", spl_object_hash($inst1), get_class($inst1));
$inst2 = ChildClass2::getInstance($obj);
printf("I am %s, my class is %s\n", spl_object_hash($inst2), get_class($inst2));
printf("Are we same object? %s\n", spl_object_hash($inst1) == spl_object_hash($inst2) ? 'yes' : 'NO!');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment