Call method by string?

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();

Leave a Comment