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!

 

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

EXAMPLE CODE DOWNLOAD

Source code on GitHub Gist

Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

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.

 

 

CALLBACK FUNCTION EXAMPLES

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

 

EXAMPLE 1) CLASSIC CALLBACK FUNCTION

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

// (B) PASS FUNKY() INTO CALL_USER_FUNC()
call_user_func("funky");

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 funky() into call_user_func() as a parameter.
  • The callback function gets called inside the function itselfcall_user_func() calls funky().

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

 

EXAMPLE 2) YET ANOTHER SIMPLE ONE

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

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” getFunky() function that will call back to $callback if specified.
  • So, very straightforward –
    • getFunky("funkyA") will call back to funkyA().
    • getFunky("funkyB") will call back to funkyB().

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

 

 

EXAMPLE 3) PASS PARAMETERS TO THE 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 $data.

As you can see, the main process of fetch() is to get content from a website. But depending on the callback function that is passed 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 ($callback) {
  if (is_callable($callback)) { $callback(); }
}
 
// (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 ($callback) {
  // (B1) FUNCTION IN OBJECT
  if (is_array($callback)) { call_user_func($callback); }
 
  // (B2) "REGULAR" CALLBACK FUNCTIONS
  else if (is_callable($callback)) { $callback(); }
}
 
// (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.

 

 

EXTRAS

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

 

LINKS & REFERENCES

 

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. Required fields are marked *