Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of times a PHP class is created

Tags:

oop

php

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?

like image 556
joeybaker Avatar asked Oct 08 '10 18:10

joeybaker


People also ask

How can I count the number of objects created in PHP?

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.

How do you count the number of instances in a class?

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.

What is the use of count () function in PHP?

The count() function returns the number of elements in an array.

How to count number PHP?

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.


2 Answers

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;
?>
like image 179
Colin Hebert Avatar answered Sep 22 '22 06:09

Colin Hebert


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.

like image 39
Nathan Long Avatar answered Sep 19 '22 06:09

Nathan Long