【发布时间】:2015-03-31 16:08:23
【问题描述】:
我有这样的代码:
class Server {
private $stopper;
public function setStopper() { $this->stopper = TRUE; }
public function startServer() {
$consumer = new Consumer();
$consumer->onConsume(function($data) {
global $consumer;
// some processing
if( ?? ) { // how to access stopper here??
$consumer->stop();
// also how to access stopServer() here??
}
});
$consumer->consume();
}
public function stopServer() { ... }
}
除非调用setStopper(),否则此代码位于应该永远运行的文件中。到目前为止,我有 set_time_limit 在一段时间后停止代码。但我需要实现setStopper 方式,这样我就可以在需要时停止服务器,而不是“过一会儿”。
我需要这个,因为onConsume 连接到流式 API 并在有新数据可用时运行匿名回调,并且由于某些锁定问题,我不想在超时时终止 php 应用程序。我想优雅地停止服务器。
谁能告诉我如何访问回调中的stopper 或stopServer?我可以使用以下语法吗?
...(function($data) use ($this) {...
我也想过在回调中存储类值,但是setStopper是动态调用的,值可能不会更新!
有没有更好的方法来处理这种情况?
【问题讨论】:
标签: php class callback anonymous-function