I'm trying to figure out how callbacks can come in useful in PHP. I found this tutorial:
http://www.phpriot.com/articles/php-callbacks
which gives an example of a script which downloads an RSS feed every 2 seconds (its put on sleep(2)) and rather than wait until the script has finished (which could take a long time if theres a lot of RSS feeds to download) to output the results, it prints the results each time it downloads a single RSS feed. This sounds useful, but I tested it out:
<?php // this function simulates downloading data from a site function downloadFromSites($sites, $callback = null) { $ret = array(); foreach ($sites as $site) { sleep(5); $xmlDoc = new DOMDocument(); $data = $xmlDoc->load($xml); $sxml = simplexml_import_dom($data); // 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); echo '<br>'; } } // imaginary list of sites to download from $sites = array( 'http://news.google.com/news?ned=us&topic=h&output=rss', 'http://rss.msnbc.msn.com/id/3032091/device/rss/rss.xml' // 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 ?>
and it doesn't work. It just prints the results when the script has finished running. What am I doing wrong here?