Smarty调用静态类方法


Smarty call a static class method

我想在smarty模板中调用一个php方法。

我有类

class TestClass
{
    public static myMth($vars) {
        var_dump($vars);
    }
}

在我的模板中,我放了:

{TestClass::myMth($someVar)}

这行不通。我有错误:

解析错误:语法错误,意外的'myMth' (T_STRING),期望变量(T_VARIABLE)

实际上它工作没有问题(Smarty 3.1.19):

PHP:

$data['elements'] = [1,2,3,4,5,6,7,8,9,10,11];
$smarty->assign('someVar',$data);
class TestClass
{
    public static function myMth($vars) { // added function word here - you missed it in question
        var_dump($vars);
        echo "<br />test test test<br />";
    }
}
在Smarty:

{TestClass::myMth($someVar)}
输出:

array(1) { ["elements"]=> array(11) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> int(4) [4]=> int(5) [5]=> int(6) [6]=> int(7) [7]=> int(8) [8]=> int(9) [9]=> int(10) [10]=> int(11) } }
test test test

但是我不认为这是使用Smarty的最佳方式。

你应该使用:

$smarty->assign('result', TestClass::myMth($data));

为什么?这很简单。Smarty是模板引擎,你应该只在这里显示数据。你不应该启动类/方法等等。如果myMyth函数名改变或者参数改变怎么办?您需要更改Smarty模板文件。最好是只把这个方法的输出赋值给Smarty。

但是,如果你仍然想这样做,你也可以看看静态类部分在Smarty网站