Callbacks - what are they?

I hear the term “callbacks” used frequently but I do not know what it means. Can someone explain it to me and give an example? I hear it both in PHP and JS communities.

A callback is a function that is “called” dynamically at runtime.

http://php.net/manual/en/function.array-map.php

This example should illustrate how it works.


function i_am_callback ( $var ) { var_dump( $var); }
function i_call_callbacks ( $func ) { call_user_func( $func, 'cookies' ); }

i_call_callbacks( 'i_am_callback' );

Thats pretty much it…you send a function as an argument to another function and it calls the callback for whatever reason.

PHP 5.3 only: http://us2.php.net/manual/en/functions.anonymous.php


function i_call_callbacks ( $func ) { $func( 'cookies' ); }

i_call_callbacks( function ($var ) { var_dump( $var ); } );

Thanks for the code. I can see what is happening there, but as a semantic issue I do not know why it is called a “callback” yet. Any idea about this? I can see it is calling a function, but why the “back” part of callback?

I am also not clear on what the purpose of these are.

Doesn’t this do the same thing? (This is just a function using another function). I probably I do not understand the example well.


function i_am_callback($var) {
	 var_dump($var);
}

function i_call_callbacks($func) { 
	
	$var_dump_this = 'my string';
	i_am_callback($var_dump_this);
}

i_call_callbacks();  



A callback is when a function is passed as an argument (parameter) to another function. Thus the function would use the callback to achieve a purpose. Callbacks allow one to change the behavior of a function without changing the function itself.

“Doesn’t this do the same thing?” No.

I guess this is still lost on me. Sorry for being dense here and thanks for the help. Can you explain what my example fails to do that a callback would? I understand it passes a function as an argument… but what’s the point when you can just call the function you want (with the required arguments) inside the function you initially called?

here’s a better example of the comparison:



function i_call_callbacks($func) {

   // scenario 1 - no call back
    $args = 'whatever';
    i_am_callback($args);

    //versus scenario 2 - call back
    call_user_func($func, 'i am string');
}

$func = 'i_am_callback';
i_call_callbacks($func);


The key part about a callback that it is determined at runtime, meaning it’s dynamically called as a variable. In your case - it’s static, meaning it’s pre-determined what function is getting called.

This means the same wrapper function can be used to call any function - thus the wrapper function is reusable.

Imagine a telephone that when you pick up and hit dial, it only dials the same number. To change the number, you have to reprogram it. This is your example.

A function with a callback is like a telephone that you can control (from the outside <– that’s the key) which number is called. Now the phone is reusable for any phone number.

The essence of a callback function is to provide a way for you to add custom behavior to an existing functionality - without altering the existing functionality’s code.

For example, say you’re building a javascript slideshow using a 3rd party library, which does all the neat animation and all that, but everytime the image changes, you need the javascript to also update another part of the website (which the library obviously won’t). So the author of the library - if they forsaw this need - would provide a callback function, so that you have the ability to add on a custom function that you would write, after a certain action is completed, which will allow you to do whatever you want before/after one of their functions are called.

What an OUTSTANDING allegory! Great work, @wonshikee!

Thanks for the further explanation wonshikee!

I think the term “callback” is used because it allows the called method the callback the calling code.

Imagine a library function is called by the main application code. If you pass a function of the main application as a parameter into the library function it can call back to the main app’s code.

As an example, say you have written a library that is used by many applications and maybe even many companies.

Within the library it is required to test that the application user is logged in and has sufficient security clearance to run functions within your library.

Your library cannot know how user credentials are stored - it could be in a plain text file, a MySQL database, an xml file etc.

So, if functions in your library accept a parameter which is a call back function, the programmers who use your library can write a function that looks up user details (in what ever way they are stored) and returns a value to indicate “authorised” or not. This function is then passed into your library’s functions as a parameter and your function can callback that function to get the “authorised” or not info.

Kind regards,

Mike

ps I hope that made sense.

pps I expect there are other/better ways to do the authorisation thing, but it just serves as an example for this question.

Callback function is a function passed to another function in form of pointer or address. This helps in saving the computational task for the called function.

Thanks for the additional comments Mike - that helped!

christajoe, I did not understand your comment that a callback "helps in saving the computational task for the called function. " Could you elaborate?

Probably the best way to explain is with a demonstration.

Website visitors do not like to be kept waiting for a page to appear, however if the page has to perform a lot of complex calculations or retrieve then process information that takes several seconds this is when a callback comes to the rescue.

So to keep visitors happy the server sends only the bare bones of the page such as the CSS, images and any other content it can get hold of quickly from a database for instance and adds on the callback script. When the basic page has loaded the callback script fires up and asks for the server to start working on the hard stuff, once the server has done the hard work it sends the new data back and the script swaps and this new data into the page. This way the visitor has something to read and keep them occupied while they are waiting.

Example one: server working like crazy to build complete page then deliver everything at once to browser
http://bishop-test.appspot.com/?location=lambeth

Example two: older data (red headers) gets replaced by new data (green headers) using a callback
http://lovelogic.net/f-job-scan.php?location=LAMBETH%20-%20SE11&page=0#top

Other examples of this behaviour can be seen with the jQuery ‘Lazy load’ plugin
designed to load images into very long pages as the visitor scrolls down towards them rather than sending them all at once hanging
the page in the process. handy for all you bloggers out there

Torite, Ya sure.
By additional computational tasks, it means when a function is called it need not to process the additional information required to output the result. For example if a download dialogue box, calls, say, the progress bar function, to display user about the time left for download to complete, then progress bar function is simply embedded onto the download dialogue box. All the required information like the total time left for a file to completely download, is provided by the function managing the download dialogue box. So to progress bar progresses according to the events information provided by the download box function and itself need not to compute the whole task.