PHP非falsy空合并运算符
当我发现php7的空合并运算符时,我非常高兴。但现在,在实践中,我发现它不是我想象的那样: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运算符,但有一个解
$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,感谢您对开发人员心理健康的贡献。