Created
June 11, 2012 07:54
-
-
Save syavorsky/2908981 to your computer and use it in GitHub Desktop.
PHP Singleton with child classes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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