1

请参阅下面的匿名函数,我不想进入下一个for循环迭代,直到$Connected为 0

它没有按应有的方式工作...解决此问题的解决方案是什么?

 $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
  }

}
4

3 回答 3

4

您需要将 $Connected 变量传递给您的函数use

$Client->EventListener(function (EventMessage $event) use (&$Connected) {
    if ($event instanceof HangupEvent) {
        // Received Hangup Event - let terminate this while loop ..
        $Connected = 0;
     }
});
于 2012-05-10T12:32:20.493 回答
1

正如其他人所说以及文档中显示的那样,为了修改闭包内变量的值,您必须使用use (&$Conntected). 但你必须改变更多。

The while loop will be executed until $Connected is 1, that means you end up adding many many event handlers to the client... this is not what you want though.

Now, I don't know how PHP handels these event callbacks (or concurrent function calls), but I think what you need is 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
}
于 2012-05-10T12:42:25.247 回答
0

PHP 处理闭包的方式与其他语言不同。您已经明确声明要关闭哪些变量。你可以在这里阅读:http: //php.net/manual/en/functions.anonymous.php

尝试 $Client->EventListener(function(EventMessage $event) 使用 (&$Connected) {

于 2012-05-10T12:36:43.460 回答