PHP从对象方法内部调用回调函数

PHP从对象方法内部调用回调函数,php,laravel,callback,Php,Laravel,Callback,我正在构建一个调度器,它将接受一个回调函数,并在给定的延迟时间内执行该函数。下面是该功能的界面 旁注:我使用的是Laravel框架 public function testBasicTest() { $count = 0; $schedule = new NodeScheduler(); $schedule->retries(2)->delay(100000)->do(function() use ($count) { $count++;

我正在构建一个调度器,它将接受一个回调函数,并在给定的延迟时间内执行该函数。下面是该功能的界面

旁注:我使用的是Laravel框架

public function testBasicTest()
{
    $count = 0;
    $schedule = new NodeScheduler();
    $schedule->retries(2)->delay(100000)->do(function() use ($count) {
        $count++;
    });
    $this->assertEquals($count === 1);
}
这是我对这项功能的测试,正如你所看到的,我希望在测试结束时计数等于2

我的班级是这样的

class NodeScheduler
{
    protected $retries = 1;
    protected $milliseconds = 10000;

    public function __construct()
    {
        return $this;
    }

    public function retries($numberOfRetries)
    {
        $this->retries = $numberOfRetries;
        return $this;
    }

    public function delay($milliSeconds)
    {
        $this->milliSeconds = $milliSeconds;
        return $this;
    }

    public function do($callback)
    {
        for($i = 0; $i < $this->retries; $i++){
            $callback(); // <<<<<< How Do I Inject The $count Variable Here?
            usleep($this->milliseconds);
        }
        return;
    }
}
奇怪的是,我不知道$count是未定义的


我想我很接近,非常感谢你的帮助

我想你做错了两件事

首先:如前所述

$this->assertEquals($expected, $actual);
其次:从我在代码中看到的情况来看,循环将运行
$this->重试
的迭代。因此,
$this->assertEquals($expected,$actual)
应该是

$this->assertEquals(2, count);
祝你好运

当您
use()
函数内部外部作用域中的变量时,这将创建一个将该变量复制到函数内部作用域中的副本(如果您正在
use()
对象,则例外)

如果要从外部作用域导入变量并对其进行修改,则需要通过引用将其传入:

$schedule->retries(2)->delay(100000)->do(function() use (&$count) {
    $count++;
});

Edit:还有@Arno和@Oniyo指出的:要么使用
assertEquals(1,$count)
要么使用
assertTrue($count==1)

我想你想写
$this->assertEquals(1,$count)我不知道参考传递,非常感谢
$schedule->retries(2)->delay(100000)->do(function() use (&$count) {
    $count++;
});