PHP 호출 가능 키워드
예시
콜백 함수를 인수로 요구하려면 callable을 사용하십시오.
<?php
function printFormatted(callable $format, $str) {
echo $format($str);
echo "<br>";
}
function exclaim($str) { return $str . "!"; }
printFormatted("exclaim", "Hello World");
?>
정의 및 사용
callable
키워드는 함수 인수가 함수에 대한 참조가 되도록 강제하는 데 사용됩니다 .
콜러블은 다음 중 하나일 수 있습니다.
- 익명 함수
- 함수의 이름을 포함하는 문자열
- 정적 클래스 메서드를 설명하는 배열
- 객체 메서드를 설명하는 배열
더 많은 예
예시
다양한 유형의 콜러블 사용:
<?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 키워드