Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic class method invocation in PHP

Tags:

php

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); 
like image 465
VirtuosiMedia Avatar asked Oct 30 '08 19:10

VirtuosiMedia


People also ask

How to call class dynamically in php?

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.

How do you call a class method in PHP?

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).


2 Answers

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

like image 123
andy.gurin Avatar answered Oct 03 '22 18:10

andy.gurin


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 
like image 22
RodolfoNeto Avatar answered Oct 03 '22 19:10

RodolfoNeto