Php 如何检查是否已分配Smarty变量?

Php 如何检查是否已分配Smarty变量?,php,smarty,template-engine,Php,Smarty,Template Engine,如何检查特定值是否已分配给Smarty,如果未分配(默认)值 答复: if ($this->cismarty->get_template_vars('test') === null) { $this->cismarty->assign('test', 'Default value'); } Smarty 2 if ($smarty->get_template_vars('foo') === null) { $smarty->assign('fo

如何检查特定值是否已分配给Smarty,如果未分配(默认)值

答复:

if ($this->cismarty->get_template_vars('test') === null) {
   $this->cismarty->assign('test', 'Default value');
}

Smarty 2

if ($smarty->get_template_vars('foo') === null) 
{
   $smarty->assign('foo', 'some value');
}
Smarty 3

if ($smarty->getTemplateVars('foo') === null) 
{
   $smarty->assign('foo', 'some value');
}

请注意,对于Smarty 3,您将不得不使用
$Smarty->getTemplateVars

您肯定可以做到:

if (!isset($smarty['foo'])) 
{
    $smarty->assign('foo', 'some value');
}
get\u template\u vars()
如果未设置变量,将返回null,因此可以执行以下操作

if ($smarty->get_template_vars('test') === null) {
    echo "'test' is not assigned or is null";
}
但是,如果您分配了一个变量,但将其设置为null,则该检查将失败,在这种情况下,您可以这样做

$tmp = $smarty->get_template_vars();
if (!array_key_exists('test', $tmp)) {
    echo "'test' is not assigned";
}

这不就是检查它的值是否不为空吗?如果null是正确的赋值怎么办?在这种情况下,行为应该是“如果未设置值(null),则设置默认值”。此外,isset()不能用于检查函数的返回值,但是您可以只检查值本身。谢谢Andy。get_template_vars()设计用于在不存在的变量上返回NULL。我不确定这是否正确,get_template_vars将始终返回有效的引用,因此您无法使用isset()进行检查,但在
.tpl
文件中如何?这不适用于Smarty 3。出现错误
无法将Smarty类型的对象用作数组