请参阅下面的匿名函数,我不希望在for
为0之前进行下一个$Connected
循环迭代
它应该是怎么回事......解决这个问题的解决方案是什么?
$Client = new Client();
for ($i = 1; $i <= 5; $i++) {
$result = $Client->Action(rand(1,1000));
if ($result->isSuccess()) {
$Connected = 1;
}
// Stay in the loop until 'HangupEvent' received
while ($Connected) {
$Client->EventListener(function (EventMessage $event) {
if ($event instanceof HangupEvent) {
// Received Hangup Event - let terminate this while loop ..
$Connected = 0;
}
});
// If $Connected = 0; then go to next `for` loop iteration
}
}
答案 0 :(得分:4)
您需要使用use
$Client->EventListener(function (EventMessage $event) use (&$Connected) {
if ($event instanceof HangupEvent) {
// Received Hangup Event - let terminate this while loop ..
$Connected = 0;
}
});
答案 1 :(得分:1)
正如其他人所说的那样shown in the documentation,为了修改闭包内变量的值,你必须使用use (&$Conntected)
传递它。但你必须做更多的改变。
while
循环将执行,直到$Connected
为1
,这意味着您最终会向客户端添加许多事件处理程序...但这不是您想要的。
现在,我不知道PHP如何处理这些事件回调(或并发函数调用),但我认为你需要的是sleep
:
$Client->EventListener(function (EventMessage $event) use (&$Conntected) {
if ($event instanceof HangupEvent) {
// Received Hangup Event - let terminate this while loop ..
$Connected = false;
}
});
while($Connected) {
sleep(500); // delay execution for 500 milliseconds, then check again
}
答案 2 :(得分:0)
PHP处理闭包的方式与其他语言不同。您已经具体声明了要关闭的变量。您可以在此处阅读:http://php.net/manual/en/functions.anonymous.php
尝试$ Client-&gt; EventListener(函数(EventMessage $ event)使用(&amp; $ Connected){