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!
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.
When you want one function to execute only after another function has completed its execution, we use callback functions in JavaScript. It needs to pass as a parameter to other functions to make a function callback.
Example: Using a Callback FunctionThe sayName() function is passed as an argument to the greet() function. The setTimeout() method executes the greet() function only after 2 seconds. However, the sayName() function waits for the execution of the greet() function.
In simple language, If a reference of a function is passed to another function as an argument to call it, then it will be called as a Callback function. In C, a callback function is a function that is called through a function pointer. In C++ STL, functors are also used for this purpose.
Defination
A callbacks/callable is a simple function(either it is anonymous or named function) that we pass to another function as function parameter which in the result returns that passed function.
Example
function iWillReturnCallback($callBackHere){
return $callBackHere;
}
function iAmCallBack(){
echo "I am returned with the help of another function";
}
iWillReturnCallback(iAmCallBack());
//--Output -> I am returned with the help of another function
Don't be confused
There are some default functions in php that accepts the name of the callback function as a string in their parameter because of avoiding conflicting between the constant name and function name. So don't be confused in these kind of things.
A callback is either a function, an object instance' method, or a static method on a class. Either way, it's kind of a function pointer. In some languages, functions are a specific type. So you could assign a function to a variable. These are generally called function oriented languages. A good example is Javascript.
In PHP, a callback can be any of:
$fn = 'foo'; // => foo()
$fn = array($obj, 'foo'); // => $obj->foo()
$fn = array('Foo', 'bar'); // => Foo::bar()
See the manual entry for is_callable
.
You can invoke a callback with the rather verbose function call_user_func
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With