나는 그것을 권하고 싶지 않다 :-) 새로운라는 이유 이잖아 클래스의 새로운 인스턴스를 생성 (사람들은 새로운 완전히 새로운 개체를 의미한다고 생각). 그러나 그때 나는 싱글 톤의 사용을 다시 생각하지 않을 것이다.
이 코드의 기본 개념은 싱글 톤 주위에 래퍼가 있다는 것입니다. 랩퍼를 통해 액세스되는 모든 함수와 변수는 실제로 싱글 톤에 영향을줍니다. 아래의 코드는 마술 방법과 SPL 인터페이스를 많이 구현하지 않습니다하지만 그들은
코드
/**
* Superclass for a wrapper around a singleton implementation
*
* This class provides all the required functionality and avoids having to copy and
* paste code for multiple singletons.
*/
class SingletonWrapper{
private $_instance;
/**
* Ensures only derived classes can be constructed
*
* @param string $c The name of the singleton implementation class
*/
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;
}
}
/**
* A test singleton implementation. This shouldn't be constructed and getInstance shouldn't
* be used except by the MySingleton wrapper class.
*/
class MySingletonImpl{
private static $instance = null;
public function &getInstance(){
if (self::$instance === null){
self::$instance = new self();
}
return self::$instance;
}
//test functions
public $foo = 1;
public function bar(){
static $var = 1;
echo $var++;
}
}
/**
* A wrapper around the MySingletonImpl class
*/
class MySingleton extends SingletonWrapper{
public function __construct(){
parent::__construct('MySingletonImpl');
}
}
예
$s1 = new MySingleton();
echo $s1->foo; //1
$s1->foo = 2;
$s2 = new MySingleton();
echo $s2->foo; //2
$s1->bar(); //1
$s2->bar(); //2
를 필요한 경우에 추가 할 수는 완벽하지 않습니다
이 질문은 문제가되지 않습니다. 패턴을 완성하는 방법을 좋아하지 않는다고 불평하는 것입니다. -1 –
이것은 매우 정당한 질문입니다. +1은 -1이 아니기 때문에 +1 : P – Leo
PHP를 사용하지 마십시오 ?? – Kevin