简体   繁体   English

PHP模板中的未定义变量

[英]Undefined variables in PHP template

I use PHP as a template language in my view layer, Is it possible to make following a little cleaner and more concise? 我在视图层中使用PHP作为模板语言,是否可以使编写的内容更简洁,更简洁?

//in temp.phtlm
<?= (isset($user['name'])) ? $user['name'] : null; ?> 

Unfortunately we can not even define a function for that: 不幸的是,我们甚至不能为此定义一个函数:

// as you know yet a notice is generated when calling function with undefined parameter
function out($var)
{
        return (isset($var)) ? htmlentities($var) : null;
}

There is no short hand method to do that quicker, no. 没有捷径可以更快地做到这一点,不是。 Any other method would throw an error if $var did not exist at that point. 如果此时$ var不存在,则任何其他方法都将引发错误。

Depending on your structure/templating system you could use a class to store your var's and use the magic methods __get, __set, __isset, __unset to call your variables. 根据您的结构/模板系统,您可以使用一个类来存储您的var,并使用魔术方法__get,__ set,__ isset和__unset来调用变量。 Those methods could then just return null if the var didnt exist. 如果var不存在,则这些方法将只返回null。 This would require quite a change in your code though. 不过,这将需要对代码进行相当大的更改。 You can find the manual about magic methods here: http://php.net/manual/en/language.oop5.magic.php 您可以在此处找到有关魔术方法的手册: http : //php.net/manual/zh/language.oop5.magic.php

As for your original code, i would write it like this: 至于您的原始代码,我会这样写:

<?php echo ( isset($var) ? $var : null ); ?> 
//in temp.phtlm
<?=$var?>

//in whatever_your_script_name.php
$template->var = isset($var) ? htmlentities(whatever(convert(encode($var)))) : '';
$template->render('temp.phtml');

使用@运算符是最简单的选择。

<?= @$user['name']; ?> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM