跳至内容

对象

Smarty 允许通过模板访问 PHP 对象

注意

当您将对象分配给/注册到模板中时,请确保从模板访问的所有属性和方法仅用于演示目的。很容易通过对象注入应用程序逻辑,这会导致难以管理的糟糕设计。请参阅 Smarty 网站的最佳实践部分。

有两种方法可以访问它们。

分配对象

您可以将对象分配给模板,然后像访问任何其他已分配变量一样对其进行访问。

示例

<?php
// the object

class My_Object {
    public function meth1($params, $smarty_obj) {
        return 'this is my meth1';
    }
}

// We can also assign objects. assign_by_ref when possible.
$smarty->assign('myobj', new My_Object());

$smarty->display('index.tpl');

以下是您如何在 index.tpl 中访问您的对象

{$myobj->meth1('foo',$bar)}

注册对象

注册的对象使用不同的模板语法。此外,已注册的对象可以限制为某些方法或属性。但是,已注册的对象不能在对象数组中循环或分配等。

如果启用了安全性,则无法访问任何私有方法或函数(以“_”开头)。如果存在同名方法和属性,则将使用该方法。

您可以通过将其列在数组中作为第三个注册参数来限制可以访问的方法和属性。

默认情况下,通过模板传递给对象的函数以相同的方式传递,其中自定义标签获取它们。关联数组作为第一个参数传递,smarty对象作为第二个参数传递。如果你想按照传统对象参数传递的方式一次传递一个参数,将第四个注册参数设置为FALSE。

可选的第五个参数仅在format为TRUE时有效,它包含应视为块的方法列表。这意味着这些方法在模板中具有结束标签({foobar->meth2}...{/foobar->meth2}),并且方法的参数与 block标签 的参数具有相同的语法:它们获取四个参数$params$content$smarty&$repeat,它们的行为也如同块标签。

<?php
// the object

class My_Object {
    function meth1($params, $smarty_obj) {
        return 'this is my meth1';
    }
}

$myobj = new My_Object;

// registering the object
$smarty->registerObject('foobar', $myobj);

// if we want to restrict access to certain methods or properties, list them
$smarty->registerObject('foobar', $myobj, array('meth1','meth2','prop1'));

// if you want to use the traditional object parameter format, pass a boolean of false
$smarty->registerObject('foobar', $myobj, null, false);

$smarty->display('index.tpl');

以下是在index.tpl中访问对象的步骤

{* access our registered object *}
{foobar->meth1 p1='foo' p2=$bar}

{* you can also assign the output *}
{foobar->meth1 p1='foo' p2=$bar assign='output'}
the output was {$output}