phptype-hintingcallabletype-declaration

What does the keyword "callable" do in PHP


To be more exact, the "callable" used in function declaration arguments. like the one below.

function post($pattern, callable $handler) {
    $this->routes['post'][$pattern] = $handler;
    return $this;
}

How does it benefit us?

Why and how do we use it?

Here's a link to where I copied the above piece of code from: link


Solution

  • The callable type allows us to pass a callback function to the function that is being called. That is, callback function parameters allow the function being called to dynamically call code that we specify in the callable function parameter. This is useful because it allows us to pass dynamic code to be executed to a function.

    For example, one might want to call a function and the function accepts a callback function called log, which would log data in a custom way that you want.

    I hope that makes sense. For details, see this link.