Mot-clé appelable PHP
Exemple
Utilisez callable pour exiger une fonction de rappel comme argument :
<?php
function printFormatted(callable $format, $str) {
echo $format($str);
echo "<br>";
}
function exclaim($str) { return $str . "!"; }
printFormatted("exclaim", "Hello World");
?>
Définition et utilisation
Le callable
mot clé est utilisé pour forcer un argument de fonction à être une référence à une fonction.
Un appelable peut être l'un des éléments suivants :
- Une fonction anonyme
- Une chaîne contenant le nom d'une fonction
- Un tableau décrivant une méthode de classe statique
- Un tableau décrivant une méthode objet
Plus d'exemples
Exemple
Utilisation de différents types d'appelables :
<?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");
?>
❮ Mots clés PHP