I need to check if there exists an instance of class_A
,and if there does exist, get that instance.
How to do it in PHP?
As always, I think a simple example is best.
Now my problem has become:
$ins = new class_A();
How to store the instance in a static member variable of class_A
when instantiating?
It'll be better if the instance can be stored when calling __construct()
. Say, it should work without limitation on how it's instantiated.
The instanceof keyword is used to check if an object belongs to a class. The comparison returns true if the object is an instance of the class, it returns false if it is not.
To create an instance of a class, the new keyword must be used. An object will always be created unless the object has a constructor defined that throws an exception on error. Classes should be defined before instantiation (and in some cases this is a requirement).
Using isinstance() function, we can test whether an object/variable is an instance of the specified type or class such as int or list. In the case of inheritance, we can checks if the specified class is the parent class of an object. For example, isinstance(x, int) to check if x is an instance of a class int .
The GetInstance method first checks to see if an instance exists, creating a new instance if not. This, together with the private __construct method, ensures that there can never be more than one of this class.
What you have described is essentially the singleton pattern. Please see this question for good reasons why you might not want to do this.
If you really want to do it, you could implement something like this:
class a {
public static $instance;
public function __construct() {
self::$instance = $this;
}
public static function get() {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
}
$a = a::get();
What you ask for is impossible (Well, perhaps not in a technical sense, but highly impractical). It suggests that you have a deeper misunderstanding about the purpose of objects and classes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With