call_user_func实例
<?php
function func($a,$b)
{
echo "a:" . $a ."<br>";
echo "b:" . $b;
}
//直接方法名调用
call_user_func('func', 1,2);
echo "<br>";
class MyClass{
public function func($arg){
echo 'MyClass func ' . $arg;
}
public static function staticFunc($arg){
echo "Mysql static func " . $arg;
}
}
//调用类里的普通方法和静态方法
$myClass = new MyClass();
call_user_func([$myClass,"func"],'arg');
echo "<br>";
call_user_func(["MyClass", "staticFunc"], 'arg');
echo "<br>";
class MyClass2{
function getName($username,$callback){
return call_user_func($callback,$username);
}
function upper($username){
return strtoupper($username);
}
}
//类里方法里调用
$myClass2 = new MyClass2();
echo $myClass2->getName("huyongjian",[$myClass2,"upper"]);
结果显示
a:1
b:2
MyClass func arg
Mysql static func arg
HUYONGJIAN