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


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语法(目前)。

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

是我做错了什么,还是这是一个bug在Smarty?

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

{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()}
 */