Reputation: 4608
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.
Upvotes: 0
Views: 95
Reputation: 522626
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.
Upvotes: 6
Reputation: 58454
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.
Upvotes: 1