Juh*_*nen 9 php variables isset
有没有简洁的方法来检查是否设置了变量,然后回显它而不重复相同的变量名称?
而不是这个:
<?php
if(!empty($this->variable)) {
echo '<a href="', $this->variable, '">Link</a>';
}
?>
Run Code Online (Sandbox Code Playgroud)
我正在考虑这种C风格的伪代码:
<?php
echo if(!empty($this->variable, '<a href="', %s, '">Link</a>'));
?>
Run Code Online (Sandbox Code Playgroud)
PHP有sprintf,但它并没有完全按我所希望的那样做.如果当然我可以用它来制作一个方法/功能,但肯定必须有一种"本地"的方法吗?
更新:$this->variable
如果我理解,三元操作也会重复这一部分?
echo (!empty($this->variable) ? '<a href="',$this->variable,'">Link</a> : "nothing");
Run Code Online (Sandbox Code Playgroud)
Ger*_*umm 17
你能找到的最接近的是使用简短形式的三元运算符(从PHP5.3起可用)
echo $a ?: "not set"; // will print $a if $a evaluates to `true` or "not set" if not
Run Code Online (Sandbox Code Playgroud)
但这会触发"未定义变量"通知.哪个你可以明显压制@
echo @$a ?: "not set";
Run Code Online (Sandbox Code Playgroud)
仍然,不是最优雅/最干净的解决方案.
所以,你能想到的最干净的代码是
echo isset($a) ? $a: '';
Run Code Online (Sandbox Code Playgroud)
Fel*_*Eve 14
更新:
PHP 7引入了一个新功能:Null合并运算符
这是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';
?>
Run Code Online (Sandbox Code Playgroud)
对于那些不使用PHP7的人来说,这是我原来的答案......
我用一个小函数来实现这个目的:
function ifset(&$var, $else = '') {
return isset($var) && $var ? $var : $else;
}
Run Code Online (Sandbox Code Playgroud)
例:
$a = 'potato';
echo ifset($a); // outputs 'potato'
echo ifset($a, 'carrot'); // outputs 'potato'
echo ifset($b); // outputs nothing
echo ifset($b, 'carrot'); // outputs 'carrot'
Run Code Online (Sandbox Code Playgroud)
警告:正如Inigo在下面的评论中所指出的,使用此函数的一个不良副作用是它可以修改您正在检查的对象/数组.例如:
$fruits = new stdClass;
$fruits->lemon = 'sour';
echo ifset($fruits->peach);
var_dump($fruits);
Run Code Online (Sandbox Code Playgroud)
将输出:
(object) array(
'lemon' => 'sour',
'peach' => NULL,
)
Run Code Online (Sandbox Code Playgroud)
sav*_*ode -1
isset
像这样使用php的函数:
<?php
echo $result = isset($this->variable) ? $this->variable : "variable not set";
?>
Run Code Online (Sandbox Code Playgroud)
我认为这会有所帮助。