如何检查该类的所有实例是否已完成?

时间:2014-03-07 19:35:09

标签: php

1)为了并行化一些工作,我实例化了同一个类的多个实例。

2)我只能在实例化下一批5个之前同时创建5个对象。

这就是我陷入困境的地方。 如何创建一个循环,在关闭前5个对象之前等待足够长的时间,然后再实例化另一批5个实例?

一个选项似乎是在__constructor中创建一个全局$计数器,并在每个实例完成时减少它,所以当我从全局$ counter = 5开始时,我可以在$ counter = 0时继续,但不是更简单溶液

如何快速检查class_x的所有实例是否已完成?

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您可以使用静态属性构建自己的系统。 但它与使用全球变量没什么不同。

检查示例:

class Worker
{

    public static $nrInstances = 0;
    public static $maxInstances = 2;

    public function __construct()
    {
        if (self::$nrInstances >= self::$maxInstances) {
            throw new Exception('No more instances allowed');
        }
        self::$nrInstances++;
    }

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

}


try {
    $worker1 = new Worker();
    var_dump(Worker::$nrInstances);
}
catch(Exception $e) {

}

try {
    $worker2 = new Worker();
    var_dump(Worker::$nrInstances);
}
catch(Exception $e) {

}

try {
    $worker3 = new Worker();
    var_dump(Worker::$nrInstances);
}
catch(Exception $e) {

}

unset($worker1);
var_dump(Worker::$nrInstances);

unset($worker2);
var_dump(Worker::$nrInstances);

// output: int(1) int(2) int(1) int(0)
相关问题