callable
创建于 2024-12-03 /
26
字体:
[默认]
[大]
[更大]
实例
使用 callable 要求回调函数作为参数:
<?php$cars = ["Ford", "Volvo", "BMW"];
foreach($cars as $car) {
echo $car;
echo "<br>";
if($car == "Volvo") {
break;
}
}
?> 亲自试一试 »
定义和用法
callable
关键字用于强制函数参数是对函数的引用。
可调用对象可以是以下之一:
- 匿名函数
- 包含函数名称的字符串
- 描述静态类方法的数组
- 描述对象方法的数组
更多实例
实例
使用不同类型的可调用对象:
<?phpfunction printFormatted(callable $format, $str) {
echo $format($str);
echo "<br>";
}
class MyClass {
public static function ask($str) {
return $str . "?";
}
public function brackets($str) {
return "[$str]";
}
}
// An anonymous function
$func = function($str) { return substr($str, 0, 5); };
printFormatted($func , "Hello World");
// A string containing the name of a function
printFormatted("strtoupper", "Hello World");
// An array describing a static class method
printFormatted(["MyClass", "ask"], "Hello World");
// An array describing an object method
$obj = new MyClass();
printFormatted([$obj, "brackets"], "Hello World");
?> 亲自试一试 »
❮ PHP 关键字
0 人点赞过