JavaScript
x
Class MyClass{
private $data=array('action'=>'insert');
public function insert(){
echo 'called insert';
}
public function run(){
$this->$this->data['action']();
}
}
This doesn’t work:
JavaScript
$this->$this->data['action']();
Is the only possibility to use call_user_func();
?
Advertisement
Answer
Try:
JavaScript
$this->{$this->data['action']}();
Be sure to check if the action is allowed and it is callable
JavaScript
<?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();