The callable type
Learn to make a function accept another function with the callable type declaration.
The callable type declaration
You can pass one function as a parameter to another. For this you use the callable type declaration.
Example: function apply(callable $cb, int $x): int { return $cb($x); }. Here $cb is a function; it is called with $cb($x).
callable accepts three forms: a function name string ('strtoupper'), an anonymous function, or a ['Class', 'method'] array. This flexibility makes writing callbacks easy.
Check with is_callable
Sometimes you need to know in advance whether a value is callable. is_callable($x) does this check; it returns true or false.
It is useful to validate a callback name coming from the user. is_callable('strtoupper') returns true; is_callable('nope') returns false.
If a wrong-typed value is passed to a callable parameter, PHP throws a TypeError; is_callable prevents that.
Exercise Define the apply function
Define a function apply(callable $cb, $x) that returns $cb($x). Then call apply(fn($n) => $n * 10, 5) and print the result on a new line.
Show example solution
Write function apply(callable $cb, $x) { return $cb($x); }. Then call echo apply(fn($n) => $n * 10, 5) . "\n";.
Example solution:
<?php
// Define apply and call it with an arrow function
function apply(callable $cb, $x) {
return $cb($x);
}
echo apply(fn($n) => $n * 10, 5) . "\n";
Test yourself
-
Complete the callable type declaration
<?php function apply(____ $cb, $x) { return $cb($x); } echo apply(fn($n) => $n * 10, 5) . "\n";Show answer
<?php function apply(callable $cb, $x) { return $cb($x); } echo apply(fn($n) => $n * 10, 5) . "\n"; -
Which is NOT a valid callable form?
- 'strlen'
- ['Foo', 'bar']
- function() {}
- [1, 2, 3]
Show answer
[1, 2, 3] — Correct. [1, 2, 3] is an array of numbers; it is not callable.
-
Match the callable forms
- 'strlen'
- Name string
- function() {}
- Anonymous function
- ['Foo', 'bar']
- Class method array
- is_callable()
- Checks if callable