PHP: dynamic function call, but in class?

I am trying to create an initialization function that will call several functions in a class, a quick example of the end result is this:

$foo = new bar; $foo->call('funca, do_taxes, initb'); 

This works fine with the call_user_func function, but what I really want to do is do it inside the class, I don’t know how to do it, a quick example of my inoperative code looks like this:

 class bar { public function call($funcs) { $funcarray = explode(', ', $funcs); foreach($funcarray as $func) { call_user_func("$this->$func"); //??? } } private function do_taxes() { //... } } 

What can I call a dynamic class function?

+4
source share
4 answers

This is actually much simpler than you think, since PHP allows things like variable variables (as well as variable name names):

 foreach($funcarray as $func) { $this->$func(); } 
+5
source

You need to use an array, for example Example No. 4 in the manual :

 call_user_func(array($this, $func)); 
+7
source

All you have to do is

 $this->$func(); 

EDIT - ignore the last post, I was a little hasty and got it wrong

You can do something similar instead of call_user_func for your own or custom functions

 function arf($a) {print("arf $a arf");} $x = 'strlen'; $f2 = 'arf'; print($x('four')."\n"); $f2($arg1); 

OUT

 4 arf arf 
0
source

when we want to check if a class / method of a class exists inside a class,

then this could help

inside the class ...

  $class_func = "foo"; if(method_exists($this , $class_func ) ){ $this->$class_func(); } public function foo(){ echo " i am called "; } 
0
source

Source: https://habr.com/ru/post/1335025/


All Articles