Specify the number of times a PHP class is created

I have a php class for which I create multiple instances. I would like to know how many times I created this object.

<?php
     class myObject {
         //do stuff
     }

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

Is there any way to find that I created 3 myObjects?

+3
source share
2 answers

You can create a static counter and increment it every time your constructor .

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

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

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

echo BaseClass::$counter;
?>

This ideone code

+23
source

If your class has a specific __construct () function, it will be run every time an instance is created. You can force this function to increment a class variable.

+3
source

Source: https://habr.com/ru/post/1768671/


All Articles