Count number of times a PHP class is created

2019-07-07 07:07发布

问题:

I've got a php class that I create several instances for. I'd like to get a count of how many times I've created that object.

<?php
     class myObject {
         //do stuff
     }

    $object1 = new myObject;
    $object2 = new myObject;
    $object3 = new myObject;
?>

Is there a way to find that I've created 3 myObjects?

回答1:

You can create a static counter and increment it each time your constructor is called.

<?php
class BaseClass {
    public static $counter = 0;

    function __construct() {
        self::$counter++;
    }
}

new BaseClass();
new BaseClass();
new BaseClass();

echo BaseClass::$counter;
?>


回答2:

If your class has a __construct() function defined, it will be run every time an instance is created. You could have that function increment a class variable.



标签: php oop