note 88411 added to language.oop5.patterns

From: Date: Thu, 22 Jan 2009 20:34:43 +0000
Subject: note 88411 added to language.oop5.patterns
Groups: php.notes 
Request: Send a blank email to php-notes+get-149675@lists.php.net to get a copy of this message
Hello! I want to suggest another fast and universal way to create a singleton, that can store instances any class types. The idea based on php's ability to create object's properties in run time, and magic functions support. Main trick is to create not existed property in __get method and assign to it a value of new instance of class, named as property. Code: <?php class fClassOne { public function get() { return "value 1<br>\n"; } public function __construct() { echo "fClassOne constructed<br>\n"; } } class fClassTwo { public function get() { return "value 2<br>\n"; } public function __construct() { echo "fClassTwo constructed<br>\n"; } } class fSingleton { public function __get($sClassName) { echo "isset check<br>\n"; if(!isset($this->{$sClassName})) $this->{$sClassName} = new $sClassName; return $this->{$sClassName}; } } $MySingleton = new fSingleton(); for ($i = 0; $i < 5; $i++) echo $MySingleton->fClassOne->get(); echo $MySingleton->fClassTwo->get(); echo $MySingleton->fClassTwo->get(); ?> Output: isset check fClassOne constructed value 1 value 1 value 1 value 1 value 1 isset check fClassTwo constructed value 2 value 2 ---- Server IP: 69.147.83.197 Probable Submitter: 89.109.164.5 ---- Manual Page -- http://www.php.net/manual/en/language.oop5.patterns.php Edit -- https://master.php.net/note/edit/88411 Del: integrated -- https://master.php.net/note/delete/88411/integrated Del: useless -- https://master.php.net/note/delete/88411/useless Del: bad code -- https://master.php.net/note/delete/88411/bad+code Del: spam -- https://master.php.net/note/delete/88411/spam Del: non-english -- https://master.php.net/note/delete/88411/non-english Del: in docs -- https://master.php.net/note/delete/88411/in+docs Del: other reasons-- https://master.php.net/note/delete/88411 Reject -- https://master.php.net/note/reject/88411 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#149675) next »