Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: call dynamic function, but in a class?

Tags:

oop

php

class

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?

like image 374
Tim N. Avatar asked Dec 17 '22 18:12

Tim N.


2 Answers

You need to use an array, like Example #4 in the manual:

call_user_func(array($this, $func));
like image 79
Mark Elliot Avatar answered Jan 11 '23 09:01

Mark Elliot


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();
}
like image 20
Amber Avatar answered Jan 11 '23 10:01

Amber