note 74846 added to function.get-class

From: Date: Mon, 30 Apr 2007 19:00:30 +0000
Subject: note 74846 added to function.get-class
Groups: php.notes 
Request: Send a blank email to php-notes+get-125992@lists.php.net to get a copy of this message
To yicheng zero-four at gmail dot com: Another, maybe better example where finding out the real class (not the class we are in) in static method should be quite usefull is the Singleton pattern. There is currently no way how to create an abstract Singleton class that could be used just by extending it without the need to change the extended class. Consider this example: <?php abstract class Singleton { protected static $__instance = false; public static function getInstance() { if (self::$__instance == false) { // This acctually is not what we want, $class will always be 'Singleton' :( $class = get_class(); self::$__instance = new $class(); } return self::$__instance; } } class Foo extends Singleton { // ... } $single_foo = Foo::getInstance(); ?> This piece of code will result in a fatal error saying: Cannot instantiate abstract class Singleton in ... on line 11 The best way I figured out how to avoid this requires simple but still a change of the extended (Foo) class: <?php abstract class Singleton { protected static $__instance = false; protected static function getInstance($class) { if (self::$__instance == false) { if (class_exists($class)) { self::$__instance = new $class(); } else { throw new Exception('Cannot instantiate undefined class [' . $class . ']', 1); } } return self::$__instance; } } class Foo extends Singleton { // You have to overload the getInstance method in each extended class: public static function getInstance() { return parent::getInstance(get_class()); } } $single_foo = Foo::getInstance(); ?> This is of course nothing horrible, you will propably need to change something in the extended class anyway (at least the constructor access), but still... it is just not as nice as it possibly could be ;) ---- Server IP: 195.46.80.5 Probable Submitter: 158.195.97.203 ---- Manual Page -- http://www.php.net/manual/en/function.get-class.php Edit -- https://master.php.net/note/edit/74846 Del: integrated -- https://master.php.net/note/delete/74846/integrated Del: useless -- https://master.php.net/note/delete/74846/useless Del: bad code -- https://master.php.net/note/delete/74846/bad+code Del: spam -- https://master.php.net/note/delete/74846/spam Del: non-english -- https://master.php.net/note/delete/74846/non-english Del: in docs -- https://master.php.net/note/delete/74846/in+docs Del: other reasons-- https://master.php.net/note/delete/74846 Reject -- https://master.php.net/note/reject/74846 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#125992) next »