note 74105 added to language.oop5.patterns

From: Date: Sun, 25 Mar 2007 10:12:39 +0000
Subject: note 74105 added to language.oop5.patterns
Groups: php.notes 
Request: Send a blank email to php-notes+get-124784@lists.php.net to get a copy of this message
Here's a way to make singleton classes with no extra code other than "extends Singleton" - if you use __AutoLoad() and keep each class in a separate file that is... <?php abstract class Singleton { // Cannot be instantiated by any other class protected function __Construct() { } // Cannot be cloned ever private function __Clone() { } // Create/fetch an instance of the class static public function getInstance($ClassName = null) { static $Instance; if ($Instance) { return $Instance; } elseif ($ClassName) { $Instance = new $ClassName; return $Instance; } else { return null; // or throw exception if you want... } } } function __AutoLoad($ClassName) { include "$ClassName.php"; if (is_subclass_of($ClassName, 'Singleton')) { eval($ClassName.'::getInstance($ClassName);'); } } // ClassName.php class ClassName extends Singleton { // ... Code ... } // To use $a = ClassName::getInstance(); $a->MyFunc(); ?> Of course you could do this differently - the point is that you can use __AutoLoad() to tell the single what class it is, unlike some other ways where this is done manually every time you define a singleton class. ---- Server IP: 194.145.210.3 Probable Submitter: 88.110.116.180 ---- Manual Page -- http://www.php.net/manual/en/language.oop5.patterns.php Edit -- https://master.php.net/note/edit/74105 Del: integrated -- https://master.php.net/note/delete/74105/integrated Del: useless -- https://master.php.net/note/delete/74105/useless Del: bad code -- https://master.php.net/note/delete/74105/bad+code Del: spam -- https://master.php.net/note/delete/74105/spam Del: non-english -- https://master.php.net/note/delete/74105/non-english Del: in docs -- https://master.php.net/note/delete/74105/in+docs Del: other reasons-- https://master.php.net/note/delete/74105 Reject -- https://master.php.net/note/reject/74105 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#124784) next »