PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 8, 2022

[FIXED] How to get instance of a specific class in PHP?

 July 08, 2022     class, instance, php     No comments   

Issue

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.


Solution

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();


Answered By - Tom Haigh
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing