所以我经常写这样的东西
if (!empty($someLongVar['nestedArrayKey'])) echo $someLongVar['nestedArrayKey'];
或
<?= !empty($someLongVar['nestedArrayKey']) ? $someLongVar['nestedArrayKey'] : "" ?>
我觉得这是浪费程序员宝贵的时间。有没有什么我漏掉的简写?像
这样的函数echoIf($someLongVar['nestedArrayKey'])
将为成千上万的程序员节省大量的空间和输入。
我自己写这样一个函数似乎是不可能的,因为每次我引用一个不存在的变量时,PHP都会抛出一个警告。
您可以使用@
操作符来抑制警告。
function echoIf($variable) {
if(!empty($variable))
echo $variable;
}
echoIf(@$myVariable['test']);
function ifVar($var) {
if(isset($var)) if(!empty($var)) echo $var."'n";
}