Reputation: 1941
Let's suppose that I have a class with a method getWorkDays()
that returns an Object. That object has other methods like setMonday($val)
, setTuesday($val)
..
What I'm trying to do is to call those methods dynamically:
$weekDays = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
foreach($weekDays as $weekDayName){
call_user_func($obj->getWorkDays()->set{ucfirst($weekDayName)}, array(1));
}
Any idea what I'm doing wrong? Or how can I do this?
Thanks in advance
Upvotes: 0
Views: 255
Reputation: 474
Try this:
$day = ucfirst($weekDayName);
$method = "set{$day}";
call_user_func($obj->getWorkDays()->$method, array(1));
Upvotes: 0
Reputation: 9351
it seems that you are on right track. you have syntax error in calling set()
method. you have missed ()
in this method calling. it should be something like this:
call_user_func($obj->getWorkDays()->set{ucfirst($weekDayName)}(), array(1));
or you can split it out:
$objFirst = $obj->getWorkDays();
$params = $objFirst->set{ucfirst($weekDayName)}();
call_user_func($params,array(1));
Upvotes: 0
Reputation: 3396
here the code:
$weekDayName = ucfirst($weekDayName);
$obj->set{$weekDayName}();
Upvotes: 1