First-Class Callables
A first-class callable wraps a function or a method in a Closure value. That value can sit in a variable and run later when the program calls it.
A function becomes a value
strlen is a built-in function that counts the characters in a text. The dots form stores it in a variable, and the variable then runs on the word notebook.
<?php
$length = strlen(...);
echo $length("notebook") . "\n";A method rides with its object
The hello method belongs to the Greeter object. The dots form keeps that object, so the stored value greets the name given later.
<?php
class Greeter {
public function hello($name) {
return "Hello, " . $name;
}
}
$g = new Greeter();
$say = $g->hello(...);
echo $say("Ana") . "\n";A static method needs no object
The twice method is static, so its callable names the class itself. The stored value doubles the number given to it.
<?php
class Util {
public static function twice($n) {
return $n * 2;
}
}
$fn = Util::twice(...);
echo $fn(21) . "\n";A private method reached as a value
The code method is private, so outside code cannot call it directly. A public helper inside the class builds a Closure for it with Closure::fromCallable, and that value runs outside the class.
<?php
class Vault {
private function code() {
return "X-42";
}
public function shareCode() {
return Closure::fromCallable([$this, "code"]);
}
}
$vault = new Vault();
$getCode = $vault->shareCode();
echo $getCode() . "\n";Example
<?php
class Calc {
public static function triple($n) {
return $n * 3;
}
}
$triple = Calc::triple(...);
$results = array_map($triple, [2, 4, 6]);
print_r($results);Key points
- Write the name of a function, then three dots inside round brackets, to build its Closure.
- A Closure is a value, so it can be stored, passed, and called later.
- A method callable keeps its object, so the method still runs on that object.
- A static method callable names its class, and it needs no object.
- The dots form builds the Closure without calling the function.
- A public helper inside a class can use Closure::fromCallable to hand out a Closure for a private method of that class.
In this example, a static triple method becomes a Closure through the dots form. array_map runs that one value over each number in the list. The results print as a new array holding 6, 12, and 18.
Note
A first-class callable holds one function or one method, and array_map can run that one value over a whole array.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does strlen(...) build?