php中怎么使用call_user_func动态调用方法

php中可使用call_user_func进行方法的动态调用,可以动态调用普通函数、类方法以及带参数的类方法
1.定义一个普通函数getCurrentDate,用于获取今天日期。
call_user_func带上的参数为要被调用的函数名
fucntion getCurrentDate(){
echo 'getCurrentDate:' . date('Y-m-d');
}
call_user_func('getCurrentDate');


程序会自动执行getCurrentDate函数并获得期望的结果
getCurrentDate:2016-04-13


2.定义一个类Cls53及类方法getTitle,call_user_func的输入参数变为一个数组,数组第一个元素为对象名、第二个元素为类方法名。
class Cls53{
public function getTitle(){
echo 'title';
}
}


$cls = new Cls53();
call_user_func(array($cls,'getTitle'));


程序会自动调用对象cls的方法getTitle并获得期望的结果
title


3.也可调用带参数的方法,此时将getTitle方法改为getTitle($title).
调用时,加上第二个参数,就是需要传给方法的参数
class Cls53{
public function getTitle($title){
echo $title;
}
}


$cls = new Cls53();
call_user_func(array($cls,'getTitle'),'abc');


传入的参数是abc,可获得期望的结果:
abc

猜你喜欢

转载自www.cnblogs.com/jjxhp/p/9379018.html
今日推荐