Skip to content
Advertisement

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.

Advertisement

Answer

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();
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement