4

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?

4 Answers 4

7

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

call_user_func(array($this, $func));
Sign up to request clarification or add additional context in comments.

1 Comment

+1. I tend to prefer call_user_func() or call_user_func_array() over $this->$func().
5

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();
}

1 Comment

Thank you Amber, I am glad I could connect to two and finish my script now.
0

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 

Comments

0

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 ";
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.