note 75979 added to function.get-class

From: Date: Mon, 25 Jun 2007 15:13:04 +0000
Subject: note 75979 added to function.get-class
Groups: php.notes 
Request: Send a blank email to php-notes+get-127953@lists.php.net to get a copy of this message
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. ---- Server IP: 130.208.16.26 Probable Submitter: 213.213.140.193 ---- Manual Page -- http://www.php.net/manual/en/function.get-class.php Edit -- https://master.php.net/note/edit/75979 Del: integrated -- https://master.php.net/note/delete/75979/integrated Del: useless -- https://master.php.net/note/delete/75979/useless Del: bad code -- https://master.php.net/note/delete/75979/bad+code Del: spam -- https://master.php.net/note/delete/75979/spam Del: non-english -- https://master.php.net/note/delete/75979/non-english Del: in docs -- https://master.php.net/note/delete/75979/in+docs Del: other reasons-- https://master.php.net/note/delete/75979 Reject -- https://master.php.net/note/reject/75979 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#127953) next »