note 91808 deleted from language.oop5.patterns by danbrown
| From: | danbrown@php.net | Date: | Fri, 26 Jun 2009 13:00:49 +0000 |
| Subject: | note 91808 deleted from language.oop5.patterns by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-157526@lists.php.net to get a copy of this message | ||
Note Submitter: rabe82 at gmx dot net
----
@rskret at gmail dot com
i dont think that your "correction" will work as you expect
<?php
class Example
{
private static $instance;
protected $notice = array();
protected function __construct()
{
echo 'I am constructed';
}
// The singleton method
public static function singleton()
{
if (!isset(self::$instance)) {
$c = __CLASS__;
self::$instance = new $c;
}
return self::$instance;
}
public function setNotice( $string )
{
$this->notice[$string] = true;
}
public function getNotice()
{
return array_keys($this->notice);
}
}
class Example2 extends Example
{
// Hold an instance of the class
private static $instance;
public static function singleton()
{
if (!isset(self::$instance)) {
$c = __CLASS__;
self::$instance = new $c;
return self::$instance;
}
echo "Sorry but I'm already set.";
}
}
// This will always retrieve a single instance of the class
$test = Example::singleton(); #Output: I am constructed
$test->setNotice('Milk');
$test->setNotice('Bread');
$test->setNotice('Eggs');
var_dump($test);
#Output:
/*
* object(Example)[1]
protected 'notice' =>
array
'Milk' => boolean true
'Bread' => boolean true
'Eggs' => boolean true
*/
// overwrite $test
$test = 'Oh noes!';
var_dump($test);
#Output:
/* string 'Oh noes!' (length=8)
*/
$recover = Example::singleton();
var_dump($recover);
#Output:
/*
* object(Example)[1]
protected 'notice' =>
array
'Milk' => boolean true
'Bread' => boolean true
'Eggs' => boolean true
*/
unset($test, $recover);
$test = Example2::singleton(); #Output: I am constructed
$test->setNotice('Milk');
$test->setNotice('Bread');
$test->setNotice('Eggs');
var_dump($test);
#Output:
/*
* object(Example2)[2]
protected 'notice' =>
array
'Milk' => boolean true
'Bread' => boolean true
'Eggs' => boolean true
*/
// overwrite $test
$test = 'Oh noes!';
var_dump($test);
#Output:
/* string 'Oh noes!' (length=8)
*/
$recover = Example2::singleton(); #Output: Sorry but I'm already set.
var_dump($recover);
#Output:
/* null
*/
?>
I know a lame example.
But if you want to use (and thats whats a singleton is for) in
*n nummbers of classes you need to "recover" your instance.