2

我有一个试图分配给 smarty 变量的接口。在 Smarty 3 中添加了对类内容的支持,我正在尝试利用它。

namespace Application;
interface ServerResponseCodes
{
    const FAILURE = 0;
    const SUCCESS = 1;
    const PENDING = 2;
    const INVALID = 3;
}

接着

$smarty->assign("codes", Application\ServerResponseCodes);

抛出错误

致命错误:第 16 行 /home/parvhraban/domains/src/www_root/clienttest.php 中未定义的常量“Application\ServerResponseCodes”

是否可以从 smarty 模板访问接口常量?

是否存在我只能分配初始化对象的限制?

有什么比反射类更好、更原生的解决方案吗?

$codes = new ReflectionClass ('Application\ServerResponseCodes');
$smarty->assign("codes", $codes->getConstants());
4

1 回答 1

1

此错误与 Smarty 无关,也不是 Smarty 脚本生成它。这是一个 PHP 语法问题。

通常你必须创建一个类的实例:

$smarty->assign("codes", new Application\ServerResponseCodes);

但是,在您的情况下,这将不起作用,因为接口无法自行实例化。要访问代码,我认为您需要使用另一个实现此接口的类。

class MyClass implements ServerResponseCodes {}

$smarty->assign("codes", new MyClass);

但是,看到您的问题更新,使用ReflectionClass似乎是一个更好的选择。我敢肯定还有更好的选择,但它需要对您的应用程序有更多了解。在 Smarty 模板中需要这些值似乎很奇怪。

于 2013-08-16T14:50:14.010 回答