Skip to content
Advertisement

Call method by string?

Class MyClass{
  private $data=array('action'=>'insert');
  public function insert(){
    echo 'called insert';
  }

  public function run(){
    $this->$this->data['action']();
  }
}

This doesn’t work:

$this->$this->data['action']();

Is the only possibility to use call_user_func();?

Advertisement

Answer

Try:

$this->{$this->data['action']}();

Be sure to check if the action is allowed and it is callable

<?php

$action = 'myAction';

// Always use an allow-list approach to check for validity
$allowedActions = [
    'myAction',
    'otherAction',
];

if (!in_array($action, $allowedActions, true)) {
    throw new Exception('Action is not allowed');
}

if (!is_callable([$this, $action])) {
    // Throw an exception or call some other action, e.g. $this->default()
    throw new Exception('Action is not callable');
}

// At this point we know it's an allowed action, and it is callable
$this->$action();

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement