Reputation: 53356
Is there a way to dynamically invoke a method in the same class for PHP? I don't have the syntax right, but I'm looking to do something similar to this:
$this->{$methodName}($arg1, $arg2, $arg3);
Upvotes: 115
Views: 91113
Reputation: 4110
Still valid after all these years! Make sure you trim $methodName
if it is user defined content. I could not get $this->$methodName
to work until I noticed it had a leading space.
Upvotes: 1
Reputation: 483
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
Upvotes: 15
Reputation: 3132
You can store a method in a single variable using a closure:
class test{
function echo_this($text){
echo $text;
}
function get_method($method){
$object = $this;
return function() use($object, $method){
$args = func_get_args();
return call_user_func_array(array($object, $method), $args);
};
}
}
$test = new test();
$echo = $test->get_method('echo_this');
$echo('Hello'); //Output is "Hello"
EDIT: I've edited the code and now it's compatible with PHP 5.3. Another example here
Upvotes: 2
Reputation: 3914
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
Upvotes: 212
Reputation: 41
In my case.
$response = $client->{$this->requestFunc}($this->requestMsg);
Using PHP SOAP.
Upvotes: 2
Reputation: 25263
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.
Upvotes: 4
Reputation: 105868
You can also use call_user_func()
and call_user_func_array()
Upvotes: 4
Reputation: 545518
Just omit the braces:
$this->$methodName($arg1, $arg2, $arg3);
Upvotes: 13