Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/298.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非falsy空合并运算符_Php_Operators - Fatal编程技术网

PHP非falsy空合并运算符

PHP非falsy空合并运算符,php,operators,Php,Operators,当我发现php7的空合并运算符时,我非常高兴。但现在,在实践中,我发现它不是我想象的那样: $x = ''; $y = $x ?? 'something'; // assigns '' to $y, not 'something' 我想要像C#的?操作符或python的或操作符: x = '' y = x or 'something' # assings 'something' to y 在php中是否有类似的缩写形式?不,php没有非falsy null coalesce运算符,但有一个解

当我发现php7的空合并运算符时,我非常高兴。但现在,在实践中,我发现它不是我想象的那样:

$x = '';
$y = $x ?? 'something'; // assigns '' to $y, not 'something'
我想要像C#的
操作符或python的
操作符:

x = ''
y = x or 'something' # assings 'something' to y

在php中是否有类似的缩写形式?

不,php没有非falsy null coalesce运算符,但有一个解决方法。满足
??0:

<?php

$truly = true; // anything truly
$falsy = false; // anything falsy (false, null, 0, '0', '', empty array...)
$nully = null;

// PHP 7's "null coalesce operator":
$result = $truly ?? 'default'; // value of $truly
$result = $falsy ?? 'default'; // value of $falsy
$result = $nully ?? 'default'; // 'default'
$result = $undef ?? 'default'; // 'default'

// but because that is so 2015's...:
$result = !empty($foo) ? $foo : 'default';

// ... here comes...
// ... the "not falsy coalesce" operator!
$result = $truly ??0?: 'default'; // value of $truly
$result = $falsy ??0?: 'default'; // 'default'
$result = $nully ??0?: 'default'; // 'default'
$result = $undef ??0?: 'default'; // 'default'

// explanation:
($foo ?? <somethingfalsy>) ?: 'default';
($foo if set, else <somethingfalsy>) ? ($foo if truly) : ($foo if falsy, or <somethingfalsy>);

// here is a more readable[1][2] variant:
??''?:

// [1] maybe
// [2] also, note there is a +20% storage requirement

$y=$x?:“某物”
$x
是否始终设置?如果您将其与Python的
进行比较,…
?:
就是您想要的。否则,您将不得不澄清,
$x
是否保证存在,或者如果不存在,您是否需要避免错误。不,它可能在上下文中不可用。我将使用2015版本,谢谢。除非你和每个未来的代码库贡献者每天都在使用
,只是不要在你的代码里放这样的怪物!@GrasDouble,感谢您对开发人员心理健康的贡献。