PHP Callback Functions (Very Simple Examples)

Welcome to a quick tutorial and examples of PHP callback functions. Functions are one of the most basic things that we learn in PHP, then come along with this “callback function” thing… So, just what is a callback?

In simple terms, a callback function is:

  • A function that is passed into another function as a parameter.
  • The function is then called inside the other function itself.

Yes, that’s all. Callbacks are actually simple, but yet confusing at the same time. Let us walk through some examples in this guide – Read on!

ⓘ I have included a zip file with all the example code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Callback Examples Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

CALLBACK FUNCTION EXAMPLES

All right, let us now get into the examples on PHP callback functions.

 

EXAMPLE 1) CLASSIC CALLBACK FUNCTION

1-classic.php
<?php
// (A) FUNCTION TO CALLBACK
function myFunkyFunc () { echo "YO!"; }

// (B) PASS MYFUNKYFUNC INTO CALL_USER_FUNC()
call_user_func("myFunkyFunc");

First, we have a very simple and classic example here. Remember the two “conditions” of what makes a callback function?

  • Pass a function as a parameter into another function – We pass myFunkyFunc() into call_user_func() as a parameter.
  • Callback function gets called inside the function itselfcall_user_func() will call myFunkyFunc().

For the guys who have not figured out where the name “callback” comes from – We pass myFunkyFunc() into call_user_func(), then call_user_func() calls back to myFunkyFunc(). Get it?

 

EXAMPLE 2) YET ANOTHER SIMPLE ONE

2-simple.php
// (A) FUNCTIONS TO CALL BACK
function myFunkyA () { echo "YO!"; }
function myFunkyB () { echo "MAN!"; }
 
// (B) THE "MAIN" FUNCTION
function letsGetFunky ($callMeBack) {
  if (is_callable($callMeBack)) { $callMeBack(); }
}
 
// (C) PASS CALLBACK FUNCTIONS INTO "MAIN FUNCTION"
letsGetFunky("myFunkyA");
letsGetFunky("myFunkyB");

Let us take “very simple” up a notch to “simple”. This is pretty much how a “common callback” will look like.

  • We have a “main” letsGetFunky() function that will call back to $callMeBack if specified.
  • So, very straightforward – letsGetFunky("myFunkyA") will call back to myFunkyA(), and letsGetFunky("myFunkyB") will call back to myFunkyB().

As to why we do this “dumb” way of passing a function into a function, see the following examples.

 

 

EXAMPLE 3) PASS PARAMETERS TO CALLBACK FUNCTION

3-parameters.php
<?php
// (A) "MAIN FUNCTION"
function repeater ($num, $callback) {
  return $callback($num);
}
 
// (B) CALLBACK FUNCTIONS
function twice ($num) { return $num * 2; }
function thrice ($num) { return $num * 3; }
 
// (C) RUN!
echo repeater(12, "twice"); // 24
echo repeater(12, "thrice"); // 36

Before the angry trolls scream “this is dumb, we can just call twice(12) directly and it will do the same” – Yes, the whole point of this example is to illustrate:

  • Callback functions are still functions. We can pass variables into callback functions.
  • The idea of using a callback function is to “reuse the main function, but modify the way it acts”. Read the next “practical example” below.

 

EXAMPLE 4) CURL FETCH CALLBACK

4-curl.php
<?php
// (A) "MAIN" FUNCTION - CURL FETCH
function fetch ($url, $after) {
  // (A1) FETCH CONTENT FROM URL
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  $result = curl_exec($ch);
 
  // (A2) CALLBACK AFTER CURL FETCH
  if (is_callable($after)) { $after($result); }
}
 
// (B) CALLBACK FUNCTIONS
function save ($data) { file_put_contents("demo.html", $data); }
function show ($data) { echo $data; }
 
// (C) GO!
fetch("https://en.wikipedia.org/wiki/Rule-based_system", "save");
fetch("https://code-boxx.com", "show");
  1. The “main function” fetch() will get content from your specified $url, then passes it into the $after callback function.
  2. We have 2 callback functions here. save() will save the given $data into a file, while show() will directly output it.

As you can see, the main process of fetch() is to get content from a website. But depending on the callback function you pass in, it will act very differently. That is the smart part about callback functions – Reuse a function in different ways.

 

 

EXAMPLE 5) CALLBACK FUNCTION IN CLASS

5-class-callback.php
<?php
// (A) CLASS - STATIC FUNCTION TO CALLBACK
class MyClass {
  public static function MyFunc () { echo "FOO!"; }
}
 
// (B) THE "MAIN" FUNCTION
function funky ($callMeBack) {
  if (is_callable($callMeBack)) { $callMeBack(); }
}
 
// (C) PASS STATIC FUNCTION MYFUNC() INTO FUNKY()
funky("MyClass::MyFunc");

Yep, it’s that simple – CLASS::FUNCTION if you ever need to callback a function in a class. But take note that the callback function must be static or PHP will throw an error.

 

EXAMPLE 6) CALLBACK FUNCTION IN OBJECT

6-object-callback.php
<?php
// (A) OBJECT - TO CALLBACK MYFUNC()
class MyClass {
  public function MyFunc () { echo "FOO!"; }
}
$myObj = new MyClass();
 
// (B) THE "MAIN" FUNCTION
function funky ($callMeBack) {
  // (B1) FUNCTION IN OBJECT
  if (is_array($callMeBack)) { call_user_func($callMeBack); }
 
  // (B2) "REGULAR" CALLBACK FUNCTIONS
  else if (is_callable($callMeBack)) { $callMeBack(); }
}
 
// (C) PASS OBJECT + FUNCTION TO CALL
// SINCE OBJECTS ARE NOT GLOBAL, WE HAVE TO PASS IN ENTIRE OBJECT
funky([$myObj, "MyFunc"]);

Finally, the complication comes when calling a function in an object. Since objects are not global, we have to pass in the entire object along with the callback function.

 

 

USEFUL BITS & LINKS

That’s all for the code, and here are some small extras that may be useful to you.

 

LINKS & REFERENCES

 

INFOGRAPHIC CHEAT SHEET

Callback Functions In PHP (Click to enlarge)

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you to better understand callback functions, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

2 thoughts on “PHP Callback Functions (Very Simple Examples)”

  1. Hello
    to better understand
    give exactly the example “2) ANOTHER SIMPLE EXAMPLE” but more simply the entire tutorial and then back specifically to example #2

    Why you need or you go for that callback instead of a function where you just pass the string to echo as parameter?

    I would kindly suggest to begin the tutorial with a sort of introduction to the problem that WITHOUT a call back you can’t solve OR how much code you can cut with callbacks .

    Thank you if you can teach here in the comments or implement it in the tutorial

    1. EDIT: OK, I think I catch what you mean. Example 3 – The sequential manner works too:

      $content = curlFetch("http://site.com");
      output($content);
      saveFile($content);

      Good point – Why the need for callback then? What good are callbacks for? Tutorial slightly updated. See 3 & 4 above.

Leave a Comment

Your email address will not be published.