在 Smarty 中调用静态方法,使用变量作为 class 名称

Calling static methods in Smarty, using variable as class name

我想做这样的事情:

{$foo = 'SomeClassName'}
{$foo::someStaticMethod()}

编译模板时出现错误:Fatal error: Uncaught --> Smarty: Invalid compiled template for ...

文件编译后,在尝试显示模板时,出现此错误:Parse error: syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM), expecting ',' or ';' in ...

当我检查编译后的模板时,它包含以下语句:<?php echo $_smarty_tpl->tpl_vars['foo']->value::someStaticMethod();?>,这显然是无效的 PHP 语法(目前)。

根据我对最后一个例子的理解here,Smarty应该支持这个

我是不是做错了什么,或者这是 Smarty 中的错误?

根据 Smarty 文档,它似乎只支持分配静态函数的 return 代码。你试过了吗

{assign var=foo value=SomeClassName::someStaticMethod()} 

如果这没有帮助,我建议您编写自己的插件:http://www.smarty.net/docs/en/plugins.writing.tpl, http://www.smarty.net/docs/en/api.register.plugin.tpl

类似

<?php
$smarty->registerPlugin("function","callStatic", "smarty_function_callStatic");

function smarty_function_callStatic(array $params, Smarty_Internal_Template $template)
{
  if (isset($params['callable']) && is_callable($params['callable'])
  {
    return call_user_func_array($params['callable'], $params);
  }
}

然后在 smarty 语法中使用如下:

{callStatic callable='SomeClassName::someStaticMethod()'}

{callStatic callable='SomeClassName::someStaticMethod()' param1='123' param2='123'}

编辑:

我还测试了您在问题中提到的完全相同的代码,并且它在最新版本(来自 https://github.com/smarty-php/smarty)上对我来说工作正常。输出为“123”。

我的代码示例如下:

require '../libs/Smarty.class.php';

class DemoClass {
    public static function foobar()
    {
        return '123';
    }
}

$smarty = new Smarty;
$smarty->display('index.tpl');

/**
 * index.tpl
 *
 {$foo = 'DemoClass'}
 {$foo::foobar()}
 */