Good time of day. Whether prompt there is a normal mechanism in pkhp, for creation of an array of methods. Something like this:

$action = [ 'index' => $this->indexAction], 'about' => $this->aboutAction] ]; 

and call methods in this format:

 $action['index'](5); 
  • one
    if only via call_user_func to run, then ['index' => [$this, 'indexAction']] and call_user_func($action['index']) . did not try. - Deadooshka
  • 2
    and you need to understand what this is in this case. it is possible, though so class my { public function a() { echo "a". "\n"; } public function b() { echo "b". "\n"; } } $arr = array('a', 'b'); $i = new my(); $i->{$arr[1]}(); class my { public function a() { echo "a". "\n"; } public function b() { echo "b". "\n"; } } $arr = array('a', 'b'); $i = new my(); $i->{$arr[1]}(); - splash58
  • or create a static array in the class static $names = array('a', 'b'); and $i->{my::$names[1]}(); - splash58
  • I do not really understand this construction $i->{$arr[1]}() - Sergiy
  • one
    curly brackets mean that you need to calculate the value of a variable inside brackets - and then use the result as if it were just a string. For example, if $arr[0] = 'indexAction' , then $i->{$arr[0]}() equivalent to $i->indexAction() - Aleks G

1 answer 1

Yes it is possible. Starting in PHP 5.4, you can call object methods through the [$this, 'methodName'] construct

 [$this, 'indexAction'](5); 

You can use this construction, for example,

 <?php class MyClass { public function indexAction($id) { echo "MyClass::indexAction($id)<br />"; } public function aboutAction($id) { echo "MyClass::aboutAction($id)<br />"; } public function call($name, $id = 0){ $actions = [ 'index' => [$this, 'indexAction'], 'about' => [$this, 'aboutAction'] ]; $actions[$name]($id); } } $obj = new MyClass(); $obj->call('about', 5); // MyClass::aboutAction(5)