Skip to content

从 PHP 分配的变量

从 PHP 分配的变量通过在它们之前加上美元符号($)来引用。

示例

<?php

$smarty = new Smarty();

$smarty->assign('firstname', 'Doug');
$smarty->assign('lastname', 'Evans');
$smarty->assign('meetingPlace', 'New York');

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

index.tpl 源代码:

Hello {$firstname} {$lastname}, glad to see you can make it.
<br />
{* this will not work as $variables are case sensitive *}
This weeks meeting is in {$meetingplace}.
{* this will work *}
This weeks meeting is in {$meetingPlace}.

上述代码将输出:

Hello Doug Evans, glad to see you can make it.
<br />
This weeks meeting is in . This weeks meeting is in New York.

关联数组

您还可以通过在点号(.)后指定键来引用关联数组变量。

<?php
$smarty->assign('Contacts',
    array('fax' => '555-222-9876',
        'email' => 'zaphod@slartibartfast.example.com',
        'phone' => array('home' => '555-444-3333',
            'cell' => '555-111-1234'),
    )
);
$smarty->display('index.tpl');

index.tpl 源代码:

{$Contacts.fax}<br />
{$Contacts.email}<br />
{* you can print arrays of arrays as well *}
{$Contacts.phone.home}<br />
{$Contacts.phone.cell}<br />

这将输出:

555-222-9876<br />
zaphod@slartibartfast.example.com<br />
555-444-3333<br />
555-111-1234<br />

数组索引

您可以通过索引引用数组,就像原生的 PHP 语法一样。

<?php
$smarty->assign('Contacts', array(
    '555-222-9876',
    'zaphod@slartibartfast.example.com',
    array('555-444-3333',
        '555-111-1234'),
));
$smarty->display('index.tpl');

index.tpl 源代码:

{$Contacts[0]}<br />
{$Contacts[1]}<br />
{* you can print arrays of arrays as well *}
{$Contacts[2][0]}<br />
{$Contacts[2][1]}<br />

这将输出:

555-222-9876<br />
zaphod@slartibartfast.example.com<br />
555-444-3333<br />
555-111-1234<br />

对象

从 PHP 分配的 对象 的属性可以通过在 -> 符号后指定属性名称来引用。

name:  {$person->name}<br />
email: {$person->email}<br />

这将输出:

name: Zaphod Beeblebrox<br />
email: zaphod@slartibartfast.example.com<br />