call_user_func

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

call_user_func把第一個參數(shù)作為回調(diào)函數(shù)調(diào)用

說明

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

第一個參數(shù) callback 是被調(diào)用的回調(diào)函數(shù),其余參數(shù)是回調(diào)函數(shù)的參數(shù)。

參數(shù)

callback

將被調(diào)用的回調(diào)函數(shù)(callable)。

args

0個或以上的參數(shù),被傳入回調(diào)函數(shù)。

注意:

請注意,傳入call_user_func()的參數(shù)不能為引用傳遞。

示例 #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

返回值

返回回調(diào)函數(shù)的返回值。

范例

示例 #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()來調(diào)用一個類里面的方法

<?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 把完整的函數(shù)作為回調(diào)傳入call_user_func()

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

以上例程會輸出:

[test]

注釋

注意:

在函數(shù)中注冊有多個回調(diào)內(nèi)容時(如使用 call_user_func()call_user_func_array()),如在前一個回調(diào)中有未捕獲的異常,其后的將不再被調(diào)用。

參見