当我们检查对象时如何避免 Smarty 模板中的致命错误

How to avoid FATAL error in Smarty templates while we check for objects

我正在 Smarty 模板中执行以下检查:

{{if $Pricing->getCommission()}}
    do something
{{/if}}

这是 class Pricing 的一部分:

class Pricing {
    ...
    protected $commission;

    public function getCommission() {
        return $this->commission;
    }
}

$Pricing = new Pricing();

然后我在 Smarty 模板中使用 $Pricing PHP 对象。如果 $Pricing 缺少 commission 属性,通过 getCommission() public 方法访问,这将变成致命错误,应用程序会将其抛出到视图或最好的情况是显示一个空白页。我想避免这种情况,怎么办?我无法更改接收值的方式,这意味着我无法摆脱模板上的对象。有什么建议吗?

在您的语句周围添加一个 isset 条件,例如

{{if isset($Pricing->Commission)}} ...

请注意,佣金必须是 public 属性。否则,您应该按照评论中的说明进行操作,并在 getCommission 方法

中添加一个检查

我找到了解决方案:

{{if $Pricing && $Pricing->getCommission()}}
    do something
{{/if}}

这样我将检查 $Pricing 是否不为空以及 $Pricing->getCommission() 是否也不为空。