PHP 三元运算符与空合并运算符

标签 php php-7 ternary-operator null-coalescing-operator

有人能解释一下 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/

相关文章:

php - 如何在模态中传递表的ID值

javascript - 三元运算符对变量的赋值优先级

php - 此 PHP 代码是否打开一个网站以进行 SQL 注入(inject)

php - 为什么 PHP/Laravel 不增加这个值?

php - 在 XAMPP 上安装 FFMPEG

php - 迁移到 PHP 8.0 : array_key_exists() improved performance. .. 不理解

php - 有没有办法在 PHP 中扩展特征?

linux - apache2 配置测试失败。段错误(核心已转储)操作 'configtest' 失败

Java 三元运算符设置 True 或 false

jasper-reports - 在 JasperReports 中进行比较 if else