,
내가 그렇게 기본적으로 다른 클래스의 컬 별도의 객체 1 클래스 1 컬 개체가 할 것입니다.
은 세 가지 클래스가 있다고 가정 :
MyCurl
,
Class1
및
Class2
를, 당신은 다음과 같이 될 것이다
Class1
클래스와
Class2
클래스,
솔루션에서
MyCurl
의 한 인스턴스에
MyCurl
의 하나 개의 인스턴스를 사용하려면 :
을에서 :
class MyCurl {
private static $curlInstances = array('Class1' => null, 'Class2' => null);
private function __construct(){}
public static function getInstance($class){
if(in_array($class, array_keys(self::$curlInstances))){
if(self::$curlInstances[$class] == null){
self::$curlInstances[$class] = new MyCurl();
}
return self::$curlInstances[$class];
}else{
return false;
}
}
// your code
}
class Class1{
private static $curlInstance;
public static function getCurlInstance() {
if(!isset(self::$curlInstance)){
self::$curlInstance = MyCurl::getInstance(get_class());
}
return self::$curlInstance;
}
// your code
}
class Class2{
private static $curlInstance;
public static function getCurlInstance() {
if(!isset(self::$curlInstance)){
self::$curlInstance = MyCurl::getInstance(get_class());
}
return self::$curlInstance;
}
// your code
}
설명은 아래와 같습니다210 클래스 :
$curlInstances
private static
클래스를 만듭니다. 이 배열은 특정 클래스에 대해 객체가 만들어 졌는지 여부를 확인하는 데 사용됩니다.
- 생성자 메서드를
private
으로 만듭니다. 클래스 외부에서 오브젝트가 작성되는 것을 방지합니다.
static
클래스 메서드 getInstance()
을 만듭니다. 먼저이 메소드가 Class1
또는 Class2
클래스에서 호출되었는지 여부를 확인합니다. 그렇다면 인스턴스는 특정 클래스에 대해 생성되었는지 여부를 확인합니다. 생성 된 객체가 없으면 새로운 객체가 생성되고, 그렇지 않으면 이전 객체가 메소드에 의해 반환됩니다.
Class1
및 Class2
클래스는 모두 동일합니다.이러한 클래스에서 :
- 는
MyCurl
클래스의 인스턴스를 개최 $curlInstance
private static
클래스 변수를 만듭니다.
- 싱글 패턴을 사용하여
MyCurl
클래스의 인스턴스를 얻으려면 클래스 static
클래스를 만듭니다.
는 이러한 개별 클래스에 대해 고유 한 MyCurl
인스턴스를 얻을 이렇게하려면 다음을 수행
$class1CurlInstance1 = Class1::getCurlInstance(); // returns only one instance of MyCurl class
$class2CurlInstance1 = Class2::getCurlInstance(); // returns only one instance of MyCurl class
을 그리고 다시, 단지 디버깅을 위해 다음을 수행하십시오
// Both $class1CurlInstance2 and $class2CurlInstance2 will have the same old unique MyCurl instances
$class1CurlInstance2 = Class1::getCurlInstance();
$class2CurlInstance2 = Class2::getCurlInstance();
을 *. .. 내 다른 2 개의 클래스에 사용하고 싶지만 그 클래스에서 myCurl은 하나의 인스턴스 만 갖기를 원합니다/정적이어서 다른 클래스의 모든 객체는 같은 컬을 사용할 것입니다 * 요구 사항에 따라 [Singleton pattern] (http://stackoverflow.com/questions/203336/creating-the-singleton-design-pattern-in-php5)을 찾는 것처럼 보입니다. –
디자인 타임 중에는 개체가 아닌 값만 할당 할 수 있습니다. 런타임에서는 생성자 나 팩토리에서 클래스를 초기화하여 객체를 속성에 할당 할 수 있습니다. 클래스 내에서 받아 들여지는 유일한 다른 값은 * 같은 * 클래스 내의 상수입니다. –
@RajdeepPaul 글쎄, 기본적으로 1 클래스 1 컬 오브젝트와 같이 다른 클래스의 컬 오브제를 사용하고 싶습니다. – Higeath