PHP -oproepbaar trefwoord
Voorbeeld
Gebruik callable om een callback-functie als argument te vereisen:
<?php
function printFormatted(callable $format, $str) {
echo $format($str);
echo "<br>";
}
function exclaim($str) { return $str . "!"; }
printFormatted("exclaim", "Hello World");
?>
Definitie en gebruik
Het callable
sleutelwoord wordt gebruikt om een functieargument te dwingen een verwijzing naar een functie te zijn.
Een oproepbaar kan een van de volgende zijn:
- Een anonieme functie
- Een string die de naam van een functie bevat
- Een array die een statische klassenmethode beschrijft
- Een array die een objectmethode beschrijft
Meer voorbeelden
Voorbeeld
Verschillende soorten callables gebruiken:
<?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-sleutelwoorden