Dynamic class method invocation in PHP

Solution 1:

There is more than one way to do that:

$this->{$methodName}($arg1, $arg2, $arg3);
$this->$methodName($arg1, $arg2, $arg3);
call_user_func_array(array($this, $methodName), array($arg1, $arg2, $arg3));

You may even use the reflection api http://php.net/manual/en/class.reflection.php

Solution 2:

You can use the Overloading in PHP: Overloading

class Test {

    private $name;

    public function __call($name, $arguments) {
        echo 'Method Name:' . $name . ' Arguments:' . implode(',', $arguments);
        //do a get
        if (preg_match('/^get_(.+)/', $name, $matches)) {
            $var_name = $matches[1];
            return $this->$var_name ? $this->$var_name : $arguments[0];
        }
        //do a set
        if (preg_match('/^set_(.+)/', $name, $matches)) {
            $var_name = $matches[1];
            $this->$var_name = $arguments[0];
        }
    }
}

$obj = new Test();
$obj->set_name('Any String'); //Echo:Method Name: set_name Arguments:Any String
echo $obj->get_name();//Echo:Method Name: get_name Arguments:
                      //return: Any String

Solution 3:

Just omit the braces:

$this->$methodName($arg1, $arg2, $arg3);

Solution 4:

You can also use call_user_func() and call_user_func_array()

Solution 5:

If you're working within a class in PHP, then I would recommend using the overloaded __call function in PHP5. You can find the reference here.

Basically __call does for dynamic functions what __set and __get do for variables in OO PHP5.