有人能解释一下PHP中三元运算符简写(?:)和空合并运算符(??)之间的区别吗?

他们什么时候表现不同,什么时候表现相同(如果真的发生了的话)?

$a ?: $b

VS.

$a ?? $b

当前回答

主要的区别在于

Ternary Operator expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE but on the other hand Null Coalescing Operator expression (expr1) ?? (expr2) evaluates to expr1 if expr1 is not NULL Ternary Operator expr1 ?: expr3 emit a notice if the left-hand side value (expr1) does not exist but on the other hand Null Coalescing Operator (expr1) ?? (expr2) In particular, does not emit a notice if the left-hand side value (expr1) does not exist, just like isset(). TernaryOperator is left associative ((true ? 'true' : false) ? 't' : 'f'); Null Coalescing Operator is right associative ($a ?? ($b ?? $c));

现在让我们通过例子来解释两者的区别:

三元运算符(?:)

$x='';
$value=($x)?:'default';
var_dump($value);

// The above is identical to this if/else statement
if($x){
  $value=$x;
}
else{
  $value='default';
}
var_dump($value);

空合并运算符(??)

$value=($x)??'default';
var_dump($value);

// The above is identical to this if/else statement
if(isset($x)){
  $value=$x;
}
else{
  $value='default';
}
var_dump($value);

下面的表格解释了'?? ?和?

特别注意:空合并运算符和三元运算符是一个 表达式,并且它的值不是一个变量,而是 表达式的结果。如果你想的话,知道这一点很重要 通过引用返回一个变量。语句返回$foo ??美元的酒吧;而且 返回$var == 42 ?$a: $b;在引用返回函数中 因此不工作,并发出警告。

其他回答

实用的简短回答:

Try:

var_dump('' ?: 'ok');

vs

var_dump('' ?? 'ok');

如果测试值(或变量*)为false,第一个将返回“ok”

如果测试值(或变量*)为空或未初始化/设置,第二个将返回'ok'。


*警告:如果你想用?:测试一个变量,你必须首先确保它是初始化/设置的,否则PHP将引发一个E_NOTICE(而??不会)。

对于初学者:

空合并运算符(??)

除了空值和未定义(变量/数组索引/对象属性)之外,所有内容都为真

ex:

$array = [];
$object = new stdClass();

var_export (false ?? 'second');                           # false
var_export (true  ?? 'second');                           # true
var_export (null  ?? 'second');                           # 'second'
var_export (''    ?? 'second');                           # ""
var_export ('some text'    ?? 'second');                  # "some text"
var_export (0     ?? 'second');                           # 0
var_export ($undefinedVarible ?? 'second');               # "second"
var_export ($array['undefined_index'] ?? 'second');       # "second"
var_export ($object->undefinedAttribute ?? 'second');     # "second"

这基本上是检查变量(数组索引,对象属性..Etc)是存在的,不是空的。类似于isset函数

三元运算符简写(?:)

每个假的东西(false,null,0,空字符串)都是假的,但如果它是一个未定义的,它也会是假的,但Notice会抛出

ex

$array = [];
$object = new stdClass();

var_export (false ?: 'second');                           # "second"
var_export (true  ?: 'second');                           # true
var_export (null  ?: 'second');                           # "second"
var_export (''    ?: 'second');                           # "second"
var_export ('some text'    ?? 'second');                  # "some text"
var_export (0     ?: 'second');                           # "second"
var_export ($undefinedVarible ?: 'second');               # "second" Notice: Undefined variable: ..
var_export ($array['undefined_index'] ?: 'second');       # "second" Notice: Undefined index: ..
var_export ($object->undefinedAttribute ?: 'second');     # "Notice: Undefined index: ..

希望这能有所帮助

当使用像$_GET或$_REQUEST这样的超全局变量时,你应该意识到它们可能是一个空字符串。 在这个特殊的例子中

$username = $_GET['user'] ?? 'nobody';

将失败,因为$username的值现在是一个空字符串。

所以当使用$_GET甚至$_REQUEST时,你应该像这样使用三元操作符:

$username = (!empty($_GET['user'])?$_GET['user']:'nobody';

现在$username的值是'nobody'。

其他的答案更深入,给出了很好的解释。对于那些寻求快速答案的人,

$a ?: 'fallback'是$a ?$a: 'fallback'

一美元? ?'回退'是$a = isset($a) ?$a: 'fallback'


主要的区别在于左操作符是:

一个非空的假值(0,",false,[],…) 未定义的变量

class a
{
    public $a = 'aaa';
}

$a = new a();

echo $a->a;  // Writes 'aaa'
echo $a->b;  // Notice: Undefined property: a::$b

echo $a->a ?? '$a->a does not exists';  // Writes 'aaa'

// Does not throw an error although $a->b does not exist.
echo $a->b ?? '$a->b does not exist.';  // Writes $a->b does not exist.

// Does not throw an error although $a->b and also $a->b->c does not exist.
echo $a->b->c ?? '$a->b->c does not exist.';  // Writes $a->b->c does not exist.