What does the keyword "callable" do in PHP
Asked Answered
D

7

24

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

Dead answered 13/1, 2019 at 6:44 Comment(1)
callable is just a type hint for the parameter - have a look at php.net/manual/en/language.types.callable.php for what a callable is.Bordiuk
S
8

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.

Suzannsuzanna answered 13/1, 2019 at 6:58 Comment(1)
I see, callable was a type and it was used for a type declaration. thanks a lot.Dead
B
9

It's a type hinting which tells us this function accepts the parameter $handler as a function, see this example to clarify things:

function helloWorld()
{
   echo 'Hello World!';
}
function handle(callable $fn)
{
   $fn(); // We know the parameter is callable then we execute the function.
}

handle('helloWorld'); // Outputs: Hello World!

It's a very simple example, But I hope it helps you understand the idea.

Briard answered 13/1, 2019 at 7:1 Comment(0)
S
8

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.

Suzannsuzanna answered 13/1, 2019 at 6:58 Comment(1)
I see, callable was a type and it was used for a type declaration. thanks a lot.Dead
L
3

Here is example use of using a callable as a parameter.

The wait_do_linebreak function below will sleep for a given time, then call a function with the tailing parameters given, and then echo a line break.

...$params packs the tailing parameters into an array called $params. Here it's being used to proxy arguments into the callables.

At the end of the examples you'll see a native function that takes a callable as a parameter.

<?php

function wait_do_linebreak($time, callable $something, ...$params)
{
    sleep($time);
    call_user_func_array($something, $params);
    echo "\n";
}

function earth_greeting() {
    echo 'hello earth';
}

class Echo_Two
{
    public function __invoke($baz, $bat)
    {
        echo $baz, " ", $bat;
    }
}

class Eat_Static
{
    static function another()
    {
        echo 'Another example.';
    }
}

class Foo
{
    public function more()
    {
        echo 'And here is another one.';
    }
}

wait_do_linebreak(0, 'earth_greeting');
$my_echo = function($str) {
    echo $str;
};
wait_do_linebreak(0, $my_echo, 'hello');
wait_do_linebreak(0, function() {
    echo "I'm on top of the world.";
});
wait_do_linebreak(0, new Echo_Two, 'The', 'Earth');
wait_do_linebreak(0, ['Eat_Static', 'another']);
wait_do_linebreak(0, [new Foo, 'more']);

$array = [
    'jim',
    'bones',
    'spock'
];

$word_contains_o = function (string $str) {
    return strpos($str, 'o') !== false;
};
print_r(array_filter($array, $word_contains_o));

Output:

hello earth
hello
I'm on top of the world.
The Earth
Another example.
And here is another one.
Array
(
    [1] => bones
    [2] => spock
)
Luke answered 13/1, 2019 at 8:3 Comment(0)
F
3

Callable

callable is a php data type. It simply means anything which can be called i.e. a function type. If this function is a closure, static/regular method or something else doesn't matter as long as we can call the function.

Example:

//php callable type

$callback = function() {
    return "hello world!\n";
};

class MyClass {
    static function myCallbackMethod() {
        return "static method call \n";
    }

    public function cb()
    {
        return "method call \n";
    }

    public function __invoke() {
        return "invoke \n";
    }
}

$obj = new MyClass();

// Illustrative function
function soUseful (callable $callback) {
    echo $callback();
}

soUseful($callback);
soUseful(array($obj, 'cb')); // syntax for making  method callable
soUseful(array('MyClass', 'myCallbackMethod')); // syntax for making static method callable
soUseful($obj); // Object can be made callable via __invoke()
soUseful(fn() => "hi from closure \n"); // arrow fn

//Output
//hello world!
//method call
//static method call
//invoke
//hi from closure
Flocculant answered 27/4, 2021 at 7:31 Comment(0)
S
2

A callable (callback) function is a function that is called inside another function or used as a parameter of another function

// An example callback function
function my_callback_function() {
    echo 'hello world!';
}

// Type 1: Simple callback
call_user_func('my_callback_function');

There are some cases that your function is a template for other functions, in that case, you use parameters for the callable function.

for more information: http://php.net/manual/en/language.types.callable.php

Sokul answered 13/1, 2019 at 6:56 Comment(0)
D
0

Callable is a data-type.

note: You can always check whether your variables are of type "callable" by using the built-in is_callable function, giving your variable's handler as its argument.

The "callable" keyword seen in the code, is used for a "Type declaration", also known as "type hint" in PHP 5. this is used to specify which type of argument or parameter your functions or methods accept. this is done by simply putting the "type hint" or "Type declaration" (i.e. the name of the type, like in this case, "callable") before the parameter names.

Whenever using "type hints" or "Type declarations" for your function declarations (i.e. when you've specified which types are allowed/accepted), and you're calling them giving parameters of data-types other than those specified as acceptable, an error is generated.

note: also, class names can be used if you would like to make your function require > an object instantiated from a specific class < for its respective parameter

-

References:

php manual > type-declaration

php manual > callable type

-

I'm new to coding so please correct my mistakes :)

Dead answered 14/1, 2019 at 12:6 Comment(0)
C
0

Use callable to require a callback function as an argument

We use it with argument of function it will strict to to pass callable( closure static/regular function ) when we calling the function

Example 1 not Passing a Callable in function call :

$myfuntion  = function(callable $sum){

};

// when calling myfuntion i passed integer

$myfuntion(123);

// it will not allow us to do this 

Example 2 Passing Callable in function call :

$sum = function($arr){
  echo array_sum($arr);

};

$myfuntion  = function(callable $sum){
   // do something 
};

$myfuntion($sum);
// Sum is a callable function now it will work absolutely fine

Proper Example :

$sum = function( ...$args){
  echo array_sum($args);
};

$myfun  = function(callable $sum){
  $sum(1,2,3,4,5);
};
$myfun($sum);
Capsicum answered 31/10, 2022 at 22:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.