, ( , ). .
, . , , singleton. , SPL-,
class SingletonWrapper{
private $_instance;
protected function __construct($c){
$this->_instance = &call_user_func(array($c, 'getInstance'));
}
public function __call($name, $args){
call_user_func_array(array($this->_instance, $name), $args);
}
public function __get($name){
return $this->_instance->{$name};
}
public function __set($name, $value){
$this->_instance->{$name} = $value;
}
}
class MySingletonImpl{
private static $instance = null;
public function &getInstance(){
if ( self::$instance === null ){
self::$instance = new self();
}
return self::$instance;
}
public $foo = 1;
public function bar(){
static $var = 1;
echo $var++;
}
}
class MySingleton extends SingletonWrapper{
public function __construct(){
parent::__construct('MySingletonImpl');
}
}
< >
$s1 = new MySingleton();
echo $s1->foo;
$s1->foo = 2;
$s2 = new MySingleton();
echo $s2->foo;
$s1->bar();
$s2->bar();