PHP非伪造的空合并运算符

时间:2016-11-15 10:39:30

标签: php operators

当我发现有关php7的null coalesce运算符时,我感到非常高兴。但是现在,在实践中,我发现它并不是我认为的那样:

$x = '';
$y = $x ?? 'something'; // assigns '' to $y, not 'something'

我想要像C#' ??运算符或python' or运算符:

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

在php中有没有这方面的短手?

1 个答案:

答案 0 :(得分:2)

不,PHP没有非虚假的null coalesce运算符,但有一种解决方法。见 ??0?:

<?php

$truly = true; // anything truly
$false = 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

来源:
https://gist.github.com/vlakoff/890449b0b2bbe4a1f431

相关问题