Jump to content

What are some practical uses for callback functions?


CrimpJiggler

Recommended Posts

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?

Link to comment
Share on other sites

Unlike when you execute php on the command line, output is only output once, at the end of the script execution. So when you execute your script, it will place all of your echo's into the output buffer, and then when the script has finished, it will then put print the output buffer to the screen.

Link to comment
Share on other sites

Since PHP's userspace output buffering allows you to nest output buffers, we must ensure to end output buffering on all and any buffers currently capturing output.

Also, PHP uses output buffering by default so a call to flush() must be made to force output to the browser.

<?php 
    while( ob_get_level() ){     #  while ob_get_level() returns a value other than 0
        echo ob_get_clean();     #  echo the contents of the current output buffer and disable that buffer.
    }
    # now we've disabled all output buffers started.
    echo 'We can echo this, flush, and sleep! Now, Let\'s wait 2 minutes!';
    flush(); # force this output to browser
    $min = 0;
    while($min > 2){
        echo '<br />We are at minute '.$min++;
        flush();
        sleep(60);
    }
    echo '<br />And we\'re done!';
Edited by objnoob
Link to comment
Share on other sites

Sorry, I made a mistake in the code. This will work:

while($min < 2){    # while minute less than 2

}

Also, for this code to work one would need to call this set_time_limit function before sleep(60);

set_time_limit(0); # allow the script to run indefinitely
Edited by objnoob
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.