PHP oproepbare sleutelwoord
Voorbeeld
Gebruik oproepbaar om 'n terugbelfunksie as 'n argument te vereis:
<?php
function printFormatted(callable $format, $str) {
echo $format($str);
echo "<br>";
}
function exclaim($str) { return $str . "!"; }
printFormatted("exclaim", "Hello World");
?>
Definisie en gebruik
Die callable
sleutelwoord word gebruik om 'n funksie-argument te dwing om 'n verwysing na 'n funksie te wees.
'n Oproepbare kan een van die volgende wees:
- 'n Anonieme funksie
- 'n String wat die naam van 'n funksie bevat
- 'n Skikking wat 'n statiese klasmetode beskryf
- 'n Skikking wat 'n objekmetode beskryf
Meer voorbeelde
Voorbeeld
Gebruik verskillende tipes oproepbare:
<?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 sleutelwoorde