11-05-2010, 03:02 PM
|
#1 (permalink)
|
|
The Wanderer
Join Date: Oct 2010
Posts: 5
Thanks: 0
|
Public variable in singleton do not survive
Hi,
I am trying to use singleton in my application. I believed singleton object can hold public variables to be used at any place of my code. But it does not work... Within the same request the singleton loses public vars content. Thanks to anyone who can help me :)
PHP Code:
// singleton to keep errors
class Errors {
private static $_instance;
public $errorList;
private function __construct () {
$this->errorList = array();
}
public static function getInstance() {
if (empty(self::$_instance))
self::$_instance = new Errors ();
return self::$_instance;
}
public function addError ($error) {
$this->errorList[] = $error;
}
}
// when I use the singleton first time, it holds the public value of errorList
$err = Errors::getInstance();
$err->addError('some error');
print_r ($err->errorList);
// ... some code here
// when I get the instance again within the same request, the errorList seems to have lost it's value ('some error')
$err = Errors::getInstance();
print_r ($err->errorList);
|
|
|
|