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?
PHP count() function is an in-built function available in PHP, which counts and returns the number of elements in an array. It also counts the number of properties in an object. The count() function may return 0 for the variable, which has been declared with an empty array or for the variable which is not set.
You can count number of instances of a class by creating a static file 'counter' and increment it whenever an object is instantiated. What if the unreachable objects are garbage collected? How can you track the number of non-garbage collected objects? It is simple, Override finalize() method and decrement the counter.
The count() function returns the number of elements in an array.
You can simply use the PHP count() or sizeof() function to get the number of elements or values in an array. The count() and sizeof() function returns 0 for a variable that has been initialized with an empty array, but it may also return 0 for a variable that isn't set.
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;
?>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With