PHP callable 關鍵字
示例
使用 callable 要求將一個回撥函式作為引數
<?php
function printFormatted(callable $format, $str) {
echo $format($str);
echo "<br>";
}
function exclaim($str) { return $str . "!"; }
printFormatted("exclaim", "Hello World");
?>
自己動手試一試 »
定義和用法
callable
關鍵字用於強制函式引數成為函式引用。
callable 可以是以下之一:
- 匿名函式
- 包含函式名稱的字串
- 描述靜態類方法的陣列
- 描述物件方法的陣列
更多示例
示例
使用不同型別的 callables
<?php
function printFormatted(callable $format, $str) {
echo $format($str);
echo "<br>";
}
class MyClass {
public static function ask($str) {
return $str . "?";
}
public function brackets($str) {
return "[$str]";
}
}
// 匿名函式
$func = function($str) { return substr($str, 0, 5); };
printFormatted($func , "Hello World");
// 包含函式名稱的字串
printFormatted("strtoupper", "Hello World");
// 描述靜態類方法的陣列
printFormatted(["MyClass", "ask"], "Hello World");
// 描述物件方法的陣列
$obj = new MyClass();
printFormatted([$obj, "brackets"], "Hello World");
?>
自己動手試一試 »
❮ PHP 關鍵字