note 89537 added to language.oop5.patterns
| From: | Talraith at osu1 dot php dot net | Date: | Thu, 12 Mar 2009 16:42:53 +0000 |
| Subject: | note 89537 added to language.oop5.patterns | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-151789@lists.php.net to get a copy of this message | ||
Building on vaddsm(at)gmail.com's idea...
I think a simpler option is to have a loader class/object and then the actual class. It keeps your
class more secure in that you are defining the visibility on $instances and you keep your class neat
and tidy.
I found this useful when trying to use the singleton method on a class that extends another class.
<?php
class module_loader {
private static $instances;
public static function getInstance($module_name) {
if (!isset(self::$instances[$module_name])) {
self::$instances[$module_name] = new $module_name();
}
return self::$instances[$module_name];
}
}
class module_base {
proteced $name;
public function __construct() {
// Do initialization stuff here
}
public final function SomePermanentFunction() {
// Perform function actions
}
}
class module_test extends module_base {
public $my_var;
public function __construct() {
parent::__construct();
$this->name = 'test';
$this->my_var = '';
}
public function ModuleSpecificFunction() {
}
}
?>
So then once you have all of that defined, you can then use it like such:
<?php
// Get first instance and set value
$instance1 = module_loader::getInstance('module_test');
$instance1->my_var = 'abc';
print "Instance 1 Var = " . $instance1->my_var;
// Create second instance and check value
$instance2 = module_loader::getInstance('module_test');
print "Instance 2 Var = " . $instance2->my_var;
// Set value on second instance, check first instance
$instance2->my_var = 'def';
print "Instance 1 Var = " . $instance1->my_var;
?>
The output would then look like this:
Instance 1 Var = abc
Instance 2 Var = abc
Instance 1 Var = def
Thus $instance1 and $instance2 are created using the factory pattern but they both point back to the
same object (singleton pattern).
----
Server IP: 69.147.83.197
Probable Submitter: 63.173.0.25
----
Manual Page -- http://www.php.net/manual/en/language.oop5.patterns.php
Edit -- https://master.php.net/note/edit/89537
Del: integrated -- https://master.php.net/note/delete/89537/integrated
Del: useless -- https://master.php.net/note/delete/89537/useless
Del: bad code -- https://master.php.net/note/delete/89537/bad+code
Del: spam -- https://master.php.net/note/delete/89537/spam
Del: non-english -- https://master.php.net/note/delete/89537/non-english
Del: in docs -- https://master.php.net/note/delete/89537/in+docs
Del: other reasons-- https://master.php.net/note/delete/89537
Reject -- https://master.php.net/note/reject/89537
Search -- https://master.php.net/manage/user-notes.php