note 83343 added to language.oop5.patterns
| From: | krisdover at hotmail dot com | Date: | Wed, 21 May 2008 15:43:30 +0000 |
| Subject: | note 83343 added to language.oop5.patterns | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-139588@lists.php.net to get a copy of this message | ||
The Singleton pattern shown in the above example can still be broken by object serialization. e.g.
<?
class SingleFoo{
private static $instance;
public $identity = "in the end, there can be only one foo\n";
private function __construct() {}
public static function getInstance(){
if(!self::$instance){
self::$instance = new SingleFoo();
}
return self::$instance;
}
public function setIdentity($identity){
$this->identity = $identity;
}
public function getIdentity(){
return $this->identity;
}
}
$foo = unserialize( serialize(SingleFoo::getInstance()) );
$foo->setIdentity("new foo on the block\n");
print(SingleFoo::getInstance()->getIdentity());
print($foo->getIdentity());
// result:
// in the end, there can be only one foo
// new foo on the block
?>
A possible solution to this problem involves using the magic method __wakeup() in the Singleton
class to enforce the Singleton pattern during unserialization:
<?
class Singleton{
// ....
public function __wakeup(){
if(!self::$instance){
self::$instance = $this;
}else{
trigger_error("Unserializing this instance while another exists voilates the
Singleton pattern",
E_USER_ERROR);
}
}
// ....
}
?>
The unserialization would be permitted if it does not result in additional instances of the
Singleton, and instances restored in this way would still be accessible via the Singleton static
factory method.
Kris Dover
----
Server IP: 202.89.58.1
Probable Submitter: 203.97.101.252
----
Manual Page -- http://www.php.net/manual/en/language.oop5.patterns.php
Edit -- https://master.php.net/note/edit/83343
Del: integrated -- https://master.php.net/note/delete/83343/integrated
Del: useless -- https://master.php.net/note/delete/83343/useless
Del: bad code -- https://master.php.net/note/delete/83343/bad+code
Del: spam -- https://master.php.net/note/delete/83343/spam
Del: non-english -- https://master.php.net/note/delete/83343/non-english
Del: in docs -- https://master.php.net/note/delete/83343/in+docs
Del: other reasons-- https://master.php.net/note/delete/83343
Reject -- https://master.php.net/note/reject/83343
Search -- https://master.php.net/manage/user-notes.php