是否有一种简洁的方法来检查变量是否已设置,然后回显它而不重复相同的变量名称?
而不是这个:
<?php
if(!empty($this->variable)) {
echo '<a href="', $this->variable, '">Link</a>';
}
?>
我正在思考这个 C 风格伪代码中的一些内容:
<?php
echo if(!empty($this->variable, '<a href="', %s, '">Link</a>'));
?>
PHP 有 sprintf,但它并没有完全达到我的期望。如果我当然可以用它制作一个方法/函数,但肯定有一种方法可以“本地”完成它?
更新: 三元运算也会重复
$this->variable
部分,如果我理解的话?
echo (!empty($this->variable) ? '<a href="',$this->variable,'">Link</a> : "nothing");
最接近您要查找的内容的是使用三元运算符的缩写形式(自 PHP5.3 起可用)
echo $a ?: "not set"; // will print $a if $a evaluates to `true` or "not set" if not
但这会触发“未定义变量”通知。您可以使用
@
明显抑制它
echo @$a ?: "not set";
仍然不是最优雅/干净的解决方案。
因此,您可以期望的最干净的代码是
echo isset($a) ? $a: '';
更新:
PHP 7 引入了一个新功能:空合并运算符
这是来自 php.net 的示例。
<?php
// Fetches the value of $_GET['user'] and returns 'nobody'
// if it does not exist.
$username = $_GET['user'] ?? 'nobody';
// This is equivalent to:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';
// Coalescing can be chained: this will return the first
// defined value out of $_GET['user'], $_POST['user'], and
// 'nobody'.
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
?>
对于那些还没有使用 PHP7 的人,这是我原来的答案...
我用一个小函数来实现这个:
function ifset(&$var, $else = '') {
return isset($var) && $var ? $var : $else;
}
示例:
$a = 'potato';
echo ifset($a); // outputs 'potato'
echo ifset($a, 'carrot'); // outputs 'potato'
echo ifset($b); // outputs nothing
echo ifset($b, 'carrot'); // outputs 'carrot'
警告:正如 Inigo 在下面的评论中指出的那样,使用此函数的一个不良副作用是它可以修改您正在检查的对象/数组。例如:
$fruits = new stdClass;
$fruits->lemon = 'sour';
echo ifset($fruits->peach);
var_dump($fruits);
将输出:
(object) array(
'lemon' => 'sour',
'peach' => NULL,
)
PHP 没有内置函数。 但如果您使用 Laravel,您可以在刀片模板中使用一个方便的快捷方式:
<div>{{ $myvar ?? 'N/A' }}</div>
其中$myvar存在时显示,否则设置使用默认值(此处定义为'N/A')
isset
函数:
<?php
echo $result = isset($this->variable) ? $this->variable : "variable not set";
?>
我认为这会有所帮助。