Aufrufbares PHP - Schlüsselwort
Beispiel
Verwenden Sie Callable, um eine Callback-Funktion als Argument anzufordern:
<?php
function printFormatted(callable $format, $str) {
echo $format($str);
echo "<br>";
}
function exclaim($str) { return $str . "!"; }
printFormatted("exclaim", "Hello World");
?>
Definition und Verwendung
Das callable
Schlüsselwort wird verwendet, um zu erzwingen, dass ein Funktionsargument eine Referenz auf eine Funktion ist.
Ein Callable kann eines der folgenden sein:
- Eine anonyme Funktion
- Eine Zeichenfolge, die den Namen einer Funktion enthält
- Ein Array, das eine statische Klassenmethode beschreibt
- Ein Array, das eine Objektmethode beschreibt
Mehr Beispiele
Beispiel
Verwendung verschiedener Arten von 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-Schlüsselwörter