It’s time for callback functions. What is a callback function? It’s just a function that’s passed as an argument to another function and is then executed inside the other function. I think it’s time to go through this concept in excruciating detail to put this behind us once and for all. We’ll cover passing anonymous functions (closures) and arrow functions as arguments to other functions, and then calling them too.

Callback functions make a lot of sense in asynchronous languages since we may not want two functions to compete for finishing times. One function might be dependent on the result of another function, so we would need the two functions to execute synchronously (one after the other).

We’re used to passing integers, strings, and even arrays as arguments into functions, but we might not be familiar with passing functions themselves as arguments into other functions.

If you’re not familiar with the concept of how functions work, I suggest that you read my other articles on the concepts. Here are a few that you might want to familiarize yourself with before proceeding.

PHP 7.x — P35: User Defined Functions

PHP 7.x — P36: Function Arguments

PHP 7.x — P37: Functions Returning Values

PHP 7.x — P38: Variable Functions

PHP 7.x — P39: Anonymous Functions

PHP 7.x — P40: use Keyword

PHP 7.x — P41: Arrow Functions

I will recap a few concepts briefly just so that the overall picture makes more sense. We’ll create a function _add_one_to_x() _that accepts one argument. The function will then add _1 _to the argument and _echo _out the result.

#software-development #web-development #computer-science #programming #php #function

PHP 7.x — P42: Callback Functions
1.30 GEEK