0

I have to check, if a class has been initialized ( if I already done: $a = new MyClass; ). How can I do this using PHP?

Thanks.

tereško
  • 56,151
  • 24
  • 92
  • 147
Dail
  • 4,058
  • 14
  • 68
  • 100
  • 2
    You mean whether a class is already in use somewhere? Not sure whether that is possible. What do you want to do, what is your end goal? – Pekka Oct 17 '11 at 07:44

3 Answers3

6

One way to do it is to let the class itself keep track of all its instances:

class MyClass {

    protected static $instances = array();

    public function __construct() {
        self::$instances[] = $this;
    }

    public static function countInstances() {
        return count(self::$instances);
    }

}

echo MyClass::countInstances();

(Take care to decrease the count/references when destroying instances, yadayada...)

You may also just want to keep better track of your variables so you don't have to figure it out later, that depends on what your goals are with this.

deceze
  • 471,072
  • 76
  • 664
  • 811
2

use

if ($a instanceof MyClass) ...
Alex
  • 27,292
  • 13
  • 89
  • 143
1

This all kinda depends on why you actually need this, but one of worst ways of achieving this would be to use singletons. Dont. ( ok .. having a global $a would be even more horrifying )

Instead you recreate the same effect by using a factory class which creates the instances of MyClass. Essentially what you do the first time is to store the created instance into a private/protected variable of the factory , and return it. Next time you check if there is already as stored value in the factory.

tereško
  • 56,151
  • 24
  • 92
  • 147