我正在用户配置文件页面上显示用户的当前状态。有3种可能的状态,并以整数形式保存在数据库中(1=帐户启用,2=帐户禁用,等等…)
为了将整数格式化为有意义的文本,我创建了一个Twig扩展,其中我在一个公共静态数组中列出了所有3种可能的状态,如下所示:
public static $aAllowedStatuses = array(
StatusModel::STATUS_DISABLED => 'Account disabled',
StatusModel::STATUS_ENABLED => 'Account enabled',
StatusModel::STATUS_TECHNICAL_PROBLEM => 'Account disabled because of technical problem'
);
我想翻译这些文本,所以我在我的小树枝扩展中注入了翻译服务,并尝试更改
StatusModel::STATUS_DISABLED => 'Account disabled'
至
StatusModel::STATUS_DISABLED => $this->translator->trans('Account disabled')
但我在我的IDE(phpStorm)中得到了这个错误:表达式不允许作为字段默认值
我做错了什么?或者有更好的方法吗?
谢谢。
在PHP中定义属性时,不能评估任何代码。
你可以做的是在构造函数中翻译它们,例如:
public function __construct(Translator $translator)
{
foreach (self::$allowedStatuses as $key => $message) {
self::$allowedStatuses[$key] = $translator->trans($message);
}
}
在数组构造中不能使用表达式。
之后你可以这样做:
$aAllowedStatuses[StatusModel::STATUS_DISABLED] => $this->translator->trans('Account disabled');