我正在尝试了解 PHP 回调。我正在使用来自phpriot.com的示例。
---------------this code-----------------------------
// this function simulates downloading data from a site
function downloadFromSites($sites, $callback = null)
{
$ret = array();
foreach ($sites as $site) {
sleep(2);
$data = 'downloaded data here';
// check if the callback is valid
if (is_callable($callback)) {
// callback is valid - call it with given arguments
call_user_func($callback, $site, $data);
}
// write the data for this site to return array
$ret[] = array(
'site' => $site,
'data' => $data
);
}
return $ret;
}
// define a fictional class used for the callback
class MyClass
{
// this is the callback method
public static function downloadComplete($site, $data)
{
echo sprintf("Finished downloading from %s\n", $site);
}
}
// imaginary list of sites to download from
$sites = array(
'http://www.example1.com',
'http://www.example2.com'
// more sites...
);
// start downloading and store the return data
downloadFromSites($sites, array('MyClass', 'downloadComplete'));
// we don't need to loop over the return data
// now since the callback handles that instead
当您运行此代码时,您将看到“完成下载”消息显示为每个站点都已完成,而不是最后全部。
因此,当我在控制台中运行此代码时,它工作正常:每 2 秒出现一个新行,但在浏览器窗口中我必须等到代码完成执行,然后才能看到结果。
所以问题是,为什么它在控制台中工作,而不是在浏览器窗口中工作?