Parola chiave richiamabile PHP
Esempio
Usa callable per richiedere una funzione di callback come argomento:
<?php
function printFormatted(callable $format, $str) {
echo $format($str);
echo "<br>";
}
function exclaim($str) { return $str . "!"; }
printFormatted("exclaim", "Hello World");
?>
Definizione e utilizzo
La callable
parola chiave viene utilizzata per forzare l'argomento di una funzione come riferimento a una funzione.
Un callable può essere uno dei seguenti:
- Una funzione anonima
- Una stringa contenente il nome di una funzione
- Un array che descrive un metodo di classe statico
- Un array che descrive un metodo oggetto
Altri esempi
Esempio
Utilizzo di diversi tipi di 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");
?>
❮ Parole chiave PHP