Reputation: 291
I am trying to create an initialisation function that will call multiple functions in the class, a quick example of the end result is this:
$foo = new bar;
$foo->call('funca, do_taxes, initb');
This will work fine normally with call_user_func function, but what I really want to do is do that inside the class, I haven't a clue how to do this, a quick example of my unworking code is as follows:
class bar {
public function call($funcs) {
$funcarray = explode(', ', $funcs);
foreach($funcarray as $func) {
call_user_func("$this->$func"); //???
}
}
private function do_taxes() {
//...
}
}
How would I call a dynamic class function?
Upvotes: 4
Views: 4838
Reputation: 3465
when we want to check whether a class function/method exists within the class,
then this could help
inside class...
$class_func = "foo";
if(method_exists($this , $class_func ) ){
$this->$class_func();
}
public function foo(){
echo " i am called ";
}
Upvotes: 0
Reputation: 16768
All you need to do is
$this->$func();
EDIT - disregard last post, i was a little hasty and misunderstood
You can do something similar in place of call_user_func
either for native or user functions
function arf($a) {print("arf $a arf");}
$x = 'strlen';
$f2 = 'arf';
print($x('four')."\n");
$f2($arg1);
OUT
4
arf arf
Upvotes: 0
Reputation: 526573
It's actually a lot simpler than you think, since PHP allows things like variable variables (and also variable object member names):
foreach($funcarray as $func) {
$this->$func();
}
Upvotes: 5
Reputation: 77034
You need to use an array, like Example #4 in the manual:
call_user_func(array($this, $func));
Upvotes: 7