From your comment,
I would want to have a separate object of curl in different class so basically 1 class 1 curl object.
Suppose you have three classes: MyCurl
, Class1
and Class2
, and you want to use only one instance of MyCurl
in Class1
class and one instance of MyCurl
in Class2
class, the solution would be like this:
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
}
The explanation is given below:
In MyCurl
class:
- Create a
private static
class array $curlInstances
. This array will be used to check whether an object has been created for the particular class or not.
- Make its constructor method
private
. It prevents objects from being created from being created from outside of the class.
- Create a
static
class method getInstance()
. It first checks whether this method has been called from either Class1
or Class2
class or not. If so then it checks whether an instance has been created for the particular class or not. If no object has been created then a new object will be created, otherwise the old object will be returned by the method.
Both Class1
and Class2
class are quite same. In these classes:
- Create a
private static
class variable $curlInstance
to hold the instance of MyCurl
class.
- Create a
static
class method getCurlInstance()
to get the instance of MyCurl
class using Singleton pattern.
To get unique MyCurl
instances for these individual classes, do this:
$class1CurlInstance1 = Class1::getCurlInstance(); // returns only one instance of MyCurl class
$class2CurlInstance1 = Class2::getCurlInstance(); // returns only one instance of MyCurl class
And again, just for the sake of debugging, do this:
// Both $class1CurlInstance2 and $class2CurlInstance2 will have the same old unique MyCurl instances
$class1CurlInstance2 = Class1::getCurlInstance();
$class2CurlInstance2 = Class2::getCurlInstance();