Search code examples
phpvariablesmethodsjoomlacall

how to call Joomla component method by variable?


$model = JModelLegacy::getInstance('NameOfModel', $prefix = 'my_componentModel', $config = array());

Normally, I would call the models method like this:

$this->items = $model->my_method();

In my case, I need to call the method by variable, because it is dynamic:

$this->items = $model->$variable; ...but this won't work.
$this->items = $model->{$variable}; ...this also won't work.

Does anybody know how to solve this?


Solution

  • If your code sample is right, the most likely answer is that you mean to call a method whose name is $variable, but you've forgotten the () at the end. i.e. your calling line should read:

    $this->items = $model->$variable();
    

    If, that's not a typo and you did mean to call a property of the class, it's likely that the contents of $variable don't have a matching property/method in $model.

    When using variable properpty or method names you will better off wrapping your calls in a simple check the existence of the property or method, to catch the problem before hand. e.g.

    // Check $model has a method $variable
    if (method_exists($model, $variable)
    {
        $this->items = $model->$variable();
    }
    else
    {
        ... raise a error/warning message here ...
    }
    
    // Check $model has a property $variable
    if (property_exists($model, $variable)
    {
        $this->items = $model->$variable;
    }
    else
    {
        ... raise a error/warning message here ...
    }