call_user_func
(PHP 4, PHP 5, PHP 7, PHP 8)
call_user_func — 把第一個參數作為回撥函式呼叫
參數
-
callback
-
將被呼叫的回撥函式(callable)。
-
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
返回值
返回回撥函式的返回值。
範例
示例 #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()),如在前一個回撥中有未捕獲的異常,其後的將不再被呼叫。
參見
- call_user_func_array() - 呼叫回撥函式,並把一個陣列參數作為回撥函式的參數
- is_callable() - 檢測參數是否為合法的可呼叫結構
- Variable functions
- ReflectionFunction::invoke() - Invokes function
- ReflectionMethod::invoke() - Invoke