Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get instance of a specific class in PHP?

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.

like image 659
user198729 Avatar asked Jan 21 '10 15:01

user198729


People also ask

How do I find the instance of an object in PHP?

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.

How do I instance a class in PHP?

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).

How do I find the instance of a variable?

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 .

What is GetInstance PHP?

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.


2 Answers

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();
like image 120
Tom Haigh Avatar answered Sep 20 '22 14:09

Tom Haigh


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.

like image 39
troelskn Avatar answered Sep 20 '22 14:09

troelskn