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]";
}
}
// 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