Funktionen call_user_func
Funktionen call_user_func låter dig anropa vilken callable-funktion som helst och skicka argument till den. Den tar funktionens namn eller en anonym funktion som första parameter, och följande parametrar - argument för den anropade funktionen.
Syntax
call_user_func(callable $callback, mixed ...$args): mixed
Exempel
Låt oss anropa standardfunktionen strtoupper för strängen 'hello':
<?php
$res = call_user_func('strtoupper', 'hello');
echo $res;
?>
Resultat av kodkörning:
'HELLO'
Exempel
Låt oss anropa en användardefinierad funktion med flera argument:
<?php
function sum($a, $b) {
return $a + $b;
}
$res = call_user_func('sum', 5, 3);
echo $res;
?>
Resultat av kodkörning:
8
Exempel
Användning av anonym funktion som callback:
<?php
$res = call_user_func(function($name) {
return "Hej, $name!";
}, 'John');
echo $res;
?>
Resultat av kodkörning:
'Hej, John!'
Se även
-
funktionen
call_user_func_array,
som anropar en callback-funktion med en array av parametrar -
funktionen
function_exists,
som kontrollerar om en funktion existerar