What is Callback in PHP and Why to use?

I am new PHP, I came from HTML/CSS, so yes, I am very new in this field. Now, my question is, what is Callback or it is the callable type. Why we need this function on programming. Kindly explain me in an easy way.

Kindly also let me know the use of call_user_func()

The PHP manual at http://php.net/manual/en/function.call-user-func.php gives this example:

<?php
function barber($type)
{
    echo "You wanted a $type haircut, no problem\n";
}
call_user_func('barber', "mushroom");
call_user_func('barber', "shave");
?>

The above example will output:

You wanted a mushroom haircut, no problem
You wanted a shave haircut, no problem

So call_user_func calls the ‘barber’ function at top and replaces the $type variable there with the call_user_func “mushroom” and “shave” strings.

2 Likes

So basically, with call_user_func, callable is our function name (barber) but why we need this function, I mean what is the main purpose of this function?

You use this function if you want to output the two strings of text according to the call_user_func. It is a silly example that merely illustrates call_user_func.

Someone more knowledgeable than I will have to give a more in-depth answer. You might get more answers by clicking on the link I gave earlier and reading the whole page.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.