phpoopdomcallbackfunction-calls

What is a callback function and how do I use it with OOP


I want to use the php simple HTML DOM parser to grab the image, title, date, and description from each article on a page full of articles. When looking at the API I notice it has a set_callback which Sets a callback function. However im not sure what this does or how I would use it? In one of the examples its used to call a function which strips out some stuff, im wondering if you have to use this to call all functions?

I guess im wondering why I use this, and what does it do as I have never come across a callback function before!


Solution

  • Here's a basic callback function example:

    <?php
    
    function thisFuncTakesACallback($callbackFunc)
    {
        echo "I'm going to call $callbackFunc!<br />";
        $callbackFunc();
    }
    
    function thisFuncGetsCalled()
    {
        echo "I'm a callback function!<br />";
    }
    
    thisFuncTakesACallback( 'thisFuncGetsCalled' );
    ?>
    

    You can call a function that has its name stored in a variable like this: $variable().

    So, in the above example, we pass the name of the thisFuncGetsCalled function to thisFuncTakesACallback() which then calls the function passed in.