调用动态方法

时间:2014-02-25 16:51:28

标签: php

假设我有一个带有方法getWorkDays()的类,它返回一个Object。该对象还有其他方法,例如setMonday($val)setTuesday($val) ..

我要做的是动态调用这些方法:

$weekDays = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');

foreach($weekDays as $weekDayName){                
    call_user_func($obj->getWorkDays()->set{ucfirst($weekDayName)}, array(1));     
}

知道我做错了什么吗?或者我该怎么做?

提前致谢

3 个答案:

答案 0 :(得分:1)

这里是代码:

$weekDayName = ucfirst($weekDayName);
$obj->set{$weekDayName}();

答案 1 :(得分:0)

似乎你走在正确的轨道上。调用set()方法时出现语法错误。您在此方法调用中错过了()。它应该是这样的:

call_user_func($obj->getWorkDays()->set{ucfirst($weekDayName)}(), array(1));

或者你可以把它分开:

$objFirst = $obj->getWorkDays();
$params = $objFirst->set{ucfirst($weekDayName)}();

call_user_func($params,array(1));

答案 2 :(得分:0)

试试这个:

$day = ucfirst($weekDayName);
$method = "set{$day}"; 
call_user_func($obj->getWorkDays()->$method, array(1));