简体   繁体   中英

How many instances of a class have been created

I want to know how many instances of a particular class are present in memory.

class Test
{
   public function testFunction() { return 'Test'; }
}

I create some objects:

$test1 = new Test();
$test2 = new Test();
$test3 = new Test();

How can I count the number of Test objects?

You can implement this using a static variable in your class, which you keep updated via it's constructor and destructor. Here is how:

class MyClass {
    public static $instanceCount = 0;

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

    function __destruct() {
        self::$instanceCount--;
    }
}

// create 3 instances
$a = new MyClass();
$b = new MyClass();
$c = new MyClass();
echo MyClass::$instanceCount; // outputs: 3

// implicitly lose one instance (destructor is called)
$a = "test";

echo MyClass::$instanceCount; // outputs: 2

You can try get_defined_vars function

It returns an array with defined vars, then you'll need to loop through the array an count by class. To get the class of a given variable you can use get_class function.

Maybe something like this:

function countVars() {
   $varsDefined = [];

   foreach(get_defined_vars() as $v) {
      $varClass = get_class($v);

      if (!isset($varsDefined[$varClass])) $varsDefined[$varClass] = 0;

      $varsDefined[$varClass]++;
   }

   return $varsDefined;
}

I could´t test the code so it could have some mistakes, but I think the idea is there :)

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM