【问题标题】:how to call Joomla component method by variable?如何通过变量调用 Joomla 组件方法?
【发布时间】:2014-08-30 16:49:42
【问题描述】:
$model = JModelLegacy::getInstance('NameOfModel', $prefix = 'my_componentModel', $config = array());

通常,我会这样调用模型方法:

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

就我而言,我需要通过变量调用方法,因为它是动态的:

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

有人知道怎么解决吗?

【问题讨论】:

    标签: php variables methods joomla call


    【解决方案1】:

    如果您的代码示例是正确的,那么最可能的答案是您的意思是调用名称为$variable 的方法,但您却调用了forgotten the () at the end。即您的呼叫线路应为:

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

    如果这不是拼写错误,并且您确实是要调用 property of the class,那么 $variable 的内容很可能在 $model 中没有匹配的属性/方法。

    当使用变量properptymethod 名称时,您最好将调用包装在简单的检查existence of the propertymethod 中,以便提前发现问题。例如

    // 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 ...
    }
    

    【讨论】:

    • 你是对的!我忘记了圆括号!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 2020-11-03
    • 2018-10-25
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    • 2015-12-01
    相关资源
    最近更新 更多