$x = '';
$y = $x ?? 'something'; // assigns '' to $y, not 'something'
我想要像C#' ??
运算符或python' or
运算符:
x = ''
y = x or 'something' # assings 'something' to y
在php中有没有这方面的短手?
答案 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