Mansa
Mansa

Reputation: 2325

Check if a class has been instantiated

I am trying to figure out how I can check if I have instantiated a class:

include("includes/class.parse.php"); // Include the class
$parse = new parse(); // instantiate the class

if(class_exists('parse')){
    echo 'Class instantiated!';
} else {
    echo 'Class NOT instantiated!';
}

Whether I comment out the $parse = new parse(); or not I get "Class instantiated"?

How can I check this?

Upvotes: 5

Views: 6913

Answers (2)

Rahil Wazir
Rahil Wazir

Reputation: 10132

You can use get_class

$parse = new parse(); // instantiate the class

var_dump ( get_class($parse) );  // return false if object is not instantiated

Upvotes: 6

deceze
deceze

Reputation: 522081

You know that you have instantiated a class if you have an object of that type:

$parse instanceof parse

A class does not keep track how many objects of its type have been instantiated. If you need that, you have to do it yourself:

class Foo {

    public static $instances = 0;

    public function __construct() {
        self::$instances++;
    }

}

new Foo;
new Foo;

echo 'Foo has been instantiated ', Foo::$instances, ' times';

However, I don't see a reason to do that, it's rather useless information.

Upvotes: 8

Related Questions