开发者

Is there a way to find out how many times a class has been instantiated in php?

I'm currently using this method:

class Foo {
    private static $num_instances = 0;

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

which seems to work, but I'm wondering if there's a b开发者_如何学Pythonuilt in way....


I would be surprised if there is one..
In my opinion it would be an overhead, if it is always counting the amount of created instances.


You could use xdebug using the execution trace.


You can always check $GLOBALS and count the number of class instantiations.

It wouldn't be pretty, and I would prefer to do it with a static property.


One way to go about it could be to count the instances in the $GLOBALS (as suggested by Alix):

function count_instances( $class_name ) {
    $i = 0;
    foreach ( $GLOBALS as $key => $global ) {
        if ( 'global' === $key ) continue;
        if ( 'object' === gettype($global) ) {
            if ( $class_name === get_class($global) ) $i++;
        }
    }
    return $i;
}

But note that this would not include classes instantiated without being stored in a variable. For example, it will add the instance of $var = new className(); to $GLOBALS but not simply new className(); (just the call alone without encapsulation).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜