gandalf007
gandalf007

Reputation: 87

How to reuse an object if it existed

I'm trying to determine whether or not a given object has been created. I see there are methods for class_exists and method_exists but what I'm trying to figure out is if new Foo() has been called (and hopefully figure out what variable it was assigned to, but that is not as important).

Upvotes: 3

Views: 1423

Answers (2)

simshaun
simshaun

Reputation: 21466

Edit: After seeing the reason you are needing this in the comments above, this is definitely not the way to go about it.

Here ya go. It could be optimized a little, but should work fine.

Also, passing get_defined_vars() to the function every time is necessary because that function only retrieves the vars within the scope it's called. Calling it inside the function would only give the vars within the scope of that function.

<?php
function isClassDeclared($class_name, $vars, $return_var_name = FALSE) {
    foreach ($vars AS $name => $val) {
        if (is_object($val) && $val instanceof $class_name)
            return $return_var_name ? $name : TRUE;
    }

    return FALSE;
}

class Foo {}
$foo = new Foo;

echo '<pre>';
var_dump(isClassDeclared('foo', get_defined_vars(), TRUE));
var_dump(isClassDeclared('bar', get_defined_vars(), TRUE));
echo '</pre>';

Upvotes: 0

ioseb
ioseb

Reputation: 16951

If I understand you correctly you are trying to initialize object only once. If this is the case why not to use singleton pattern? This will free you from checking of existence of object:

    class MyClass {
      private static $instance;

      private function __construct() {}

      public static function getInstance() {
        if (empty(self::$instance)) {
          self::$instance = new __CLASS__();
        }

        return self::$instance;
      }
    }

You can use this code like this:

$obj = MyClass::getInstance();

With similar approach you can define additional helper static methods which will check whether object was instantiated or not. You just need to keep instance statically inside your class.

Upvotes: 3

Related Questions