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.

1
  • 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? Commented Oct 17, 2011 at 7:44

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

use

if ($a instanceof MyClass) ... 

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.