PHP Callback Functions

PHP Callback Functions

Last Updated on Jan 08, 2023

Introduction

We have already mentioned callback functions when we were talking about array map. but now let's talk more in details about callback functions, what they are and how we have callback function in our own functions.

Callback Function as Argument

Let's say we want to define a function and this function get's 2 arguments. the first one is a value and the second one is a function that changes the value of the first argument. something like this:

function changeIt($a,$callback){
}

now all I have to do to call the $callback argument like a function is to add () after it's name. it would cause it to be called like a function. then inside () I can have arguments and since the function is going to change the value of the first argument I can pass $a to it. so the final function would be like this:

function changeIt($a,$callback){
    return $callback($a);
}

that's it. that's all we have to do.

Predefined Function

Now let's define another function call add that gets a number as an argument and adds 2 to that number and return it.

function addTwo(int $number){
    return $number + 2;
}

now we can call our own change function with a number as the first argument and the addTwo function as the second argument and run it.

Right now our addTwo function is considered as a predefined function. it means it has a name and it has been defined prior to using it in our function call.so all we have to do is to write its name as a string and PHP will take care of the rest.

function changeIt($a,$callback){
    $callback($a);
}

function addTwo(int $number){
    return $number + 2;
}

echo changeIt(12,"addTwo");
// 14

Anonymous Function

Now let's say we don't want to define our function and we want to create the function right where we write the argument. in that case we can use anonymous functions. all we have to do is to define them where we wrote the name of the function before. like this:

echo changeIt(12,function (int $number){
    return $number + 2;
});
// 14

That's it. that's how simple it is. having callback functions in our functions is very simple yet it's very powerful. a lot of builtin functions in PHP are using callback functions as well.

Conclusion

Now you know how to work with callback functions in PHP.

I recommend you to open a PHP files and try to work with both predefined and anonymous functions.

If you have any suggestions, questions, or opinions, please contact me. I’m looking forward to hearing from you!

Key takeaways

  • Callback Functions
  • Anonymous Function
  • Predefined functions

Category: programming

Tags: #php

Join the Newsletter

Subscribe to get my latest content by email.

I won't send you spam. Unsubscribe at any time.

Related Posts

Courses