PHP 版本 > 5.5 中提供了一个 Generator 类,它提供了一个名为 yield 的函数,可帮助您暂停并继续下一个函数。
generator-example.php
<?php
function myGeneratorFunction()
{
echo "One","\n";
yield;
echo "Two","\n";
yield;
echo "Three","\n";
yield;
}
// get our Generator object (remember, all generator function return
// a generator object, and a generator function is any function that
// uses the yield keyword)
$iterator = myGeneratorFunction();
输出
One
如果您想在第一个 yield 之后执行代码,请添加这些行
// get the current value of the iterator
$value = $iterator->current();
// get the next value of the iterator
$value = $iterator->next();
// and the value after that the next value of the iterator
// $value = $iterator->next();
现在你会得到输出
One
Two
如果你仔细观察 setTimeout() 会创建一个事件循环。
在 PHP 中有很多库,例如 amphp 是一种流行的库,它提供事件循环来异步执行代码。
Javascript sn-p
setTimeout(function () {
console.log('After timeout');
}, 1000);
console.log('Before timeout');
使用 Amphp 将上述 Javascript sn-p 转换为 PHP
Loop::run(function () {
Loop::delay(1000, function () {
echo date('H:i:s') . ' After timeout' . PHP_EOL;
});
echo date('H:i:s') . ' Before timeout' . PHP_EOL;
});