Funksioni call_user_func

Funksioni call_user_func lejon thirrjen e çdo funksioni callable, duke i dërguar atij argumente. Parametri i parë pranon emrin e funksionit ose një funksion anonim, parametrat pasues - argumentet për funksionin që do të thirret.

Sintaksa

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

Shembull

Le të thërrasim funksionin standard strtoupper për vargun 'hello':

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

Rezultati i ekzekutimit të kodit:

php'HELLO'

Shembull

Le të thërrasim një funksion të përdoruesit me disa argumente:

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

Rezultati i ekzekutimit të kodit:

php8

Shembull

Përdorimi i funksionit anonim si callback:

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

Rezultati i ekzekutimit të kodit:

php'Hello, John!'

Shihni gjithashtu