How to assign an object function to a variable?

class example() { function shout($var) { echo 'shout'.$var; } function whisper($var, $bool) { if($bool) { echo $var; } } } $obj = new example(); if($var) { $func = $obj->shout(); }else { $func = $obj->whisper(); } 

I want to first prepare a function variable for later use instead of putting conditions in a loop. Is there any way to do this?

+6
source share
2 answers

You can put the function name in a string:

 if($var) { $func = 'shout'; }else { $func = 'whisper'; } 

Later:

 $obj->$func 

You can also use the callback:

 if($var) { $func = array($obj, 'shout'); }else { $func = array($obj, 'whisper'); } 

Further:

 call_user_func($func); 

or

 call_user_func_array($func, $args); 
+4
source

You can call methods by name:

 if ($var) { $fn = 'shout'; } else { $fn = 'whisper'; } $obj->$fn(); 
+6
source

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


All Articles