开发者

how can i track existing number of objects of a given class without introducing a non-class member variable in php?

i get some collection of solutions please help me to find correct one.

-> add member variable increment in default constructor and decrement in dest开发者_运维知识库ructor.

-> add local variable that goes incremented in each constructor and decremented in destructor.

-> add static member variable that get incremented in each constructor and decremented in the destructor.

-> cannot be accomplished since the creation of the objects is being done dynamically via "new".

these are my four points please select me the best.


Use a static member variable:

class foo {
    protected static $instances = 0;

    public function __construct() {
        self::$instances++;
    }

    public function __destruct() {
        self::$instances--;
    }
}

But remember that you can create new instances without hitting the constructor (namely via clone, __set_state() (which is used by var_export) and unserialize )... So you'll need to add:

public function __clone() {
    self::$instances++;
}

public function __wakeup() {
    self::$instances++;
}

public static function __set_state($data) {
    $obj = new self();
    foreach ($data as $key => $value) {
        $obj->$key = $value;
    }
    return $value;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜