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 秒ごとに新しい行が表示されますが、ブラウザ ウィンドウではコードの実行が終了するまで待たなければならず、その後で結果が表示されます。
問題は、ブラウザ ウィンドウではなくコンソールで機能するのはなぜですか?