有人能解释一下 PHP 中三元运算符速记 ( ?:
) 和空合并运算符 ( ??
) 之间的区别吗?
他们什么时候表现不同,什么时候表现相同(如果发生的话)?
$a ?: $b
对比。
$a ?? $b
最佳答案
当您的第一个参数为空时,它们基本相同,只是空合并不会输出 E_NOTICE
当你有一个 undefined variable 时。 PHP 7.0 migration docs有话要说:
The null coalescing operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.
下面是一些示例代码来演示这一点:
<?php
$a = null;
print $a ?? 'b'; // b
print "\n";
print $a ?: 'b'; // b
print "\n";
print $c ?? 'a'; // a
print "\n";
print $c ?: 'a'; // Notice: Undefined variable: c in /in/apAIb on line 14
print "\n";
$b = array('a' => null);
print $b['a'] ?? 'd'; // d
print "\n";
print $b['a'] ?: 'd'; // d
print "\n";
print $b['c'] ?? 'e'; // e
print "\n";
print $b['c'] ?: 'e'; // Notice: Undefined index: c in /in/apAIb on line 33
print "\n";
有通知的行是我使用速记三元运算符而不是空合并运算符的行。但是,即使有通知,PHP 也会返回相同的响应。
执行代码:https://3v4l.org/McavC
当然,这总是假设第一个参数是
null
.一旦它不再为空,那么您最终会发现 ??
的差异。运算符将始终返回第一个参数,而 ?:
只有当第一个参数为真时才会使用简写,这取决于 PHP would type-cast things to a boolean .所以:
$a = false ?? 'f'; // false
$b = false ?: 'g'; // 'g'
然后会有
$a
等于 false
和 $b
等于 'g'
.
关于PHP 三元运算符与空合并运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46173202/