What is the use of PHP Callbacks? [closed]

There’s little use in PHP for callbacks which will be called when an action has completed, e.g.:

string('Ahmar', function ($name) { echo ... })

This is very idiomatic in languages like Javascript; but that is because Javascript has a rather different mode of execution than PHP does. In Javascript many things are usually happening at once, either in the browser due to an interactive UI, or on the server due to many parallel requests. PHP though operates in a single thread non-interactively, so there aren’t many parallel tasks happening that need to be coordinated asynchronously. Parallel execution in PHP happens through different PHP instances, not within the same PHP instance.

In Javascript you need callbacks to coordinate what should happen when something that’s happening in the background has finished processing:

foo(bar => {
    // this happens after

// this happens before

In PHP the same is achieved simply by waiting for the function to return:

// this happens before
$bar = foo();
// this happens after

(Note that there are of course exceptions to that; e.g. when writing a web socket server in PHP, you’ll get the same callback based architecture you’d see in node.js.)

So for the most part you use callbacks when you need to pass not just a value as a parameter to an algorithm, but a block of code. As a concrete example, take usort:

usort($foo, function ($a, $b) { return $a['bar'] - $b['bar']; });

This callback has nothing to do with asynchronous execution, but is for passing a custom sorting logic to a function.

Browse More Popular Posts

Leave a Comment