检查是否设置了变量,然后回显而不重复? [英] Check if variable is set and then echo it without repeating?
问题描述
是否有一种简洁的方法来检查是否设置了变量,然后在不重复相同变量名的情况下回显它?
Is there a concise way to check if a variable is set, and then echo it without repeating the same variable name?
代替此:
<?php
if(!empty($this->variable)) {
echo '<a href="', $this->variable, '">Link</a>';
}
?>
我正在考虑使用这种C风格的伪代码:
I'm thinking about something in the lines of this C-style pseudocode:
<?php
echo if(!empty($this->variable, '<a href="', %s, '">Link</a>'));
?>
PHP具有 sprintf ,但是它并没有完全满足我的期望.如果可以,我当然可以用它来做一个方法/函数,但是肯定有一种本机"做的方法吗?
PHP has sprintf, but it doesn't quite do what I was hoping for. If course I could make a method/function out of it, but surely there must be a way to do it "natively"?
更新:
如果我理解的话,三元运算还会重复$this->variable
部分?
Update:
Ternary operations would also repeat the $this->variable
part, if I understood it?
echo (!empty($this->variable) ? '<a href="',$this->variable,'">Link</a> : "nothing");
推荐答案
您能找到的最接近的是使用简短形式的三元运算符(自PHP5.3起可用)
The closest you can get to what you are looking for is using short form of ternary operator (available since PHP5.3)
echo $a ?: "not set"; // will print $a if $a evaluates to `true` or "not set" if not
但这将触发未定义的变量"通知.您可以明显地用@
But this will trigger "Undefined variable" notice. Which you can obviously suppress with @
echo @$a ?: "not set";
还是,不是最优雅/最干净的解决方案.
Still, not the most elegant/clean solution.
因此,您可以期望的最干净的代码是
So, the cleanest code you can hope for is
echo isset($a) ? $a: '';
这篇关于检查是否设置了变量,然后回显而不重复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!