How to get instance of a specific class in PHP?

71,556

Solution 1

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

Solution 2

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.

Solution 3

You should implement the Singleton pattern. http://www.developertutorials.com/tutorials/php/php-singleton-design-pattern-050729/page1.html

Solution 4

Maybe you want something like

for (get_defined_vars() as $key=>$value)
{
  if ($value instanceof class_A)
    return $value;
}

EDIT: Upon further reading, you have to jump through some hoops to get object references. So you might want return $$key; instead of return $value;. Or some other tricks to get a reference to the object.

Solution 5

The singleton pattern, with a PHP example from Wikipedia that I've added a "checkExists" method to, as it sounds like you want to check for the existence of the class without necessarily creating it if it doesn't exit:

final class Singleton 
{
    protected static $_instance;

    protected function __construct() # we don't permit an explicit call of the constructor! (like $v = new Singleton())
    { }

    protected function __clone() # we don't permit cloning the singleton (like $x = clone $v)
    { }

    public static function getInstance() 
    {
      if( self::$_instance === NULL ) {
        self::$_instance = new self();
      }
      return self::$_instance;
    }

    public static function checkExists() 
    {
      return self::$_instance;
    }
}

if(Singleton::checkExists())
   $instance = Singleton::getInstance();
Share:
71,556
user198729
Author by

user198729

Updated on December 10, 2020

Comments

  • user198729
    user198729 over 3 years

    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.