Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 检查变量是否已设置,然后不重复地回显它?_Php_Variables_Isset - Fatal编程技术网

Php 检查变量是否已设置,然后不重复地回显它?

Php 检查变量是否已设置,然后不重复地回显它?,php,variables,isset,Php,Variables,Isset,是否有一种简洁的方法来检查是否设置了变量,然后在不重复相同变量名的情况下进行回显 与此相反: <?php if(!empty($this->variable)) { echo '<a href="', $this->variable, '">Link</a>'; } ?> 像这样使用php的函数: <?php echo $result = isset($this->variable) ? $thi

是否有一种简洁的方法来检查是否设置了变量,然后在不重复相同变量名的情况下进行回显

与此相反:

<?php
    if(!empty($this->variable)) {
        echo '<a href="', $this->variable, '">Link</a>';
    }
?>
像这样使用php的函数:

<?php

  echo $result = isset($this->variable) ? $this->variable : "variable not set";

 ?>


我认为这会有所帮助。

最接近您所寻找的是使用三元运算符的简短形式(从PHP5.3开始提供)

但这将触发“未定义变量”通知。您可以使用
@

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';
?>
例如:

$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,
)

$this->变量
仍将在“do something”部分重复。我不想在命令中重复多次。(下一票不是我的…)我不知道这有什么速记。如果您经常使用它,我还是建议您为此创建一个函数。三元运算(
(bool)?value:default
)不是一个选项?通常我会使用类似的技术,但使用empty,这也说明了空strings很好的想法。遗憾的是,没有内置PHP函数,这也令人惊讶。我也想到了这一点。但是,出现了以下问题:$data=[]$数据['a']=2;echo ifset($data['b']);var_dump($数据);将返回数组(2){[“a”]=>int(2)[“b”]=>NULL}。所以ifset函数实际上修改了原始的数据对象…你在Inigo中完全正确-我从来没有意识到as通常不使用数组。看起来我们必须等到使用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'
$fruits = new stdClass;
$fruits->lemon = 'sour';
echo ifset($fruits->peach);
var_dump($fruits);
(object) array(
  'lemon' => 'sour',
  'peach' => NULL,
)