Smarty 在 if 语句中调用对象方法

Smarty call object method in if statement

所以我正在尝试将一个对象分配给 smarty。

    $a = FrameworkCore::getUserSessionObj(); // returns the object ofc
    $smarty->registerObject('global_session',$a);



  {if $global_session->isLoggedIn eq true}
    LOGGED IN
  {else}
    NO
  {/if}

现在我正在尝试将方法调用放入 if 语句中,但它不起作用。用不同的值和其他方法尝试了多次。

方法调用的输出工作正常(见下文)。

  {global_session->getType}
  {global_session->isLoggedIn}

看来 the/my if 语句失败了,但我无法让它工作。

看起来您需要在方法名称中添加括号,就像在 PHP 中一样。

{if $global_session->isLoggedIn()}
    LOGGED IN
{else}
    NO
{/if}

当您使用 registerObject() 时,您将像自定义函数一样添加它们。因此,您可以像以前一样使用 {global_session->getType}{global_session->isLoggedIn} 等表达式。但是你不能像在 {$global_session} 中那样使用它,因为你还没有用 assign() 分配这样的变量。这也意味着您不能编写如下代码:

{if global_session->isLoggedIn eq true}
...
{/if}

勾选 manual of objects in smarty:

  • One way is to register objects to the template, then use access them via syntax similar to custom functions.

  • The other way is to assign() objects to the templates and access them much like any other assigned variable.

所以当你想将对象用作变量时使用assign().