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

phpcall_user_func(callable $callback, mixed ...$args): mixed

Exempel

Låt oss anropa standardfunktionen strtoupper för strängen 'hello':

php<?php
  $res = call_user_func('strtoupper', 'hello');
  echo $res;
?>

Resultat av kodkörning:

php'HELLO'

Exempel

Låt oss anropa en användardefinierad funktion med flera argument:

php<?php
  function sum($a, $b) {
    return $a + $b;
  }
  
  $res = call_user_func('sum', 5, 3);
  echo $res;
?>

Resultat av kodkörning:

php8

Exempel

Användning av anonym funktion som callback:

php<?php
  $res = call_user_func(function($name) {
    return "Hej, $name!";
  }, 'John');
  echo $res;
?>

Resultat av kodkörning:

php'Hej, John!'

Se även