함수 처리 call_user_func

(PHP 4, PHP 5, PHP 7, PHP 8)

call_user_func — 첫 번째 매개변수에 의해 제공된 콜백 호출


설명

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

첫 번째 매개변수에서 제공한 callback을 호출하고 나머지 매개변수를 인수로 전달합니다.


매개변수

callback
호출할 콜러블입니다.
args
콜백에 전달할 매개변수가 0개 이상입니다.
메모:

call_user_func()의 매개변수는 참조로 전달되지 않습니다.

예제 #1 call_user_func() 예제 및 참조

                        
<?php
error_reporting(E_ALL);
function increment(&$var)
{
    $var++;
}

$a = 0;
call_user_func('increment', $a);
echo $a."\n";

// it is possible to use this instead
call_user_func_array('increment', array(&$a));
echo $a."\n";

// it is also possible to use a variable function
$increment = 'increment';
$increment($a);
echo $a."\n";
?>
                        
                      

위의 예는 다음을 출력합니다.

Warning: Parameter 1 to increment() expected to be a reference, value given in …
0
1
2
                      

반환 값

콜백의 반환 값을 반환합니다.


Examples

예제 #2 call_user_func() 예제

                  
<?php
function barber($type)
{
    echo "You wanted a $type haircut, no problem\n";
}
call_user_func('barber', "mushroom");
call_user_func('barber', "shave");
?>
                  
                

위의 예는 다음을 출력합니다.

You wanted a mushroom haircut, no problem
You wanted a shave haircut, no problem
                

예제 #3 네임스페이스 이름을 사용하는 call_user_func()

                  
<?php

namespace Foobar;

class Foo {
    static public function test() {
        print "Hello world!\n";
    }
}

call_user_func(__NAMESPACE__ .'\Foo::test');
call_user_func(array(__NAMESPACE__ .'\Foo', 'test'));


?>
                  
                

위의 예는 다음을 출력합니다.

Hello world!
Hello world!
                

예제 #4 call_user_func()와 함께 클래스 메서드 사용

                  
<?php

class myclass {
    static function say_hello()
    {
        echo "Hello!\n";
    }
}

$classname = "myclass";

call_user_func(array($classname, 'say_hello'));
call_user_func($classname .'::say_hello');

$myobject = new myclass();

call_user_func(array($myobject, 'say_hello'));


?>
                  
                

위의 예는 다음을 출력합니다.

Hello!
Hello!
Hello!
                

예제 #5 call_user_func()와 함께 람다 함수 사용

                  
<?php
call_user_func(function($arg) { print "[$arg]\n"; }, 'test');
?>
                  
                

위의 예는 다음을 출력합니다.

[test]
                

메모

메모: call_user_func()call_user_func_array()와 같은 함수로 등록된 콜백은 이전 콜백에서 throw된 잡히지 않은 예외가 있는 경우 호출되지 않습니다.


기타