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);
Just replace the class name with TestClass , the method name with $methodName and the method arguments with ... $args . Note that, in the later case, it doesn't matter that the method is static or non-static. One advantage is you can pass the array as a callable to a function.
When calling a class constant using the $classname :: constant syntax, the classname can actually be a variable. As of PHP 5.3, you can access a static class constant using a variable reference (Example: className :: $varConstant).
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With