PHP ternary operator vs null coalescing operator(PHP三元运算符与空合并运算符)
问题描述
谁能解释一下三元运算符简写 (?:
) 和空合并操作符 (??
) 在 PHP?
Can someone explain the differences between ternary operator shorthand (?:
) and null coalescing operator (??
) in PHP?
他们什么时候表现不同,什么时候表现相同(如果这种情况发生的话)?
When do they behave differently and when in the same way (if that even happens)?
$a ?: $b
VS.
$a ?? $b
推荐答案
当你的第一个参数为空时,除了空合并不会输出E_NOTICE
有一个未定义的变量.PHP 7.0 迁移文档 有话要说:
When your first argument is null, they're basically the same except that the null coalescing won't output an E_NOTICE
when you have an undefined variable. The PHP 7.0 migration docs has this to say:
已添加空合并运算符 (??) 作为语法糖对于需要结合使用三元的常见情况伊塞特().如果存在且不为 NULL,则返回其第一个操作数;否则返回第二个操作数.
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.
这里有一些示例代码来演示这一点:
Here's some example code to demonstrate this:
<?php
$a = null;
print $a ?? 'b'; // b
print "
";
print $a ?: 'b'; // b
print "
";
print $c ?? 'a'; // a
print "
";
print $c ?: 'a'; // Notice: Undefined variable: c in /in/apAIb on line 14
print "
";
$b = array('a' => null);
print $b['a'] ?? 'd'; // d
print "
";
print $b['a'] ?: 'd'; // d
print "
";
print $b['c'] ?? 'e'; // e
print "
";
print $b['c'] ?: 'e'; // Notice: Undefined index: c in /in/apAIb on line 33
print "
";
有通知的行是我使用速记三元运算符而不是空合并运算符的行.但是,即使有通知,PHP 也会返回相同的响应.
The lines that have the notice are the ones where I'm using the shorthand ternary operator as opposed to the null coalescing operator. However, even with the notice, PHP will give the same response back.
执行代码:https://3v4l.org/McavC
当然,这总是假设第一个参数是 null
.一旦它不再为空,那么您最终会发现不同之处在于 ??
运算符将始终返回第一个参数,而 ?:
简写仅在第一个参数为真实的,这取决于 PHP 将如何键入-将事物转换为布尔值.
Of course, this is always assuming the first argument is null
. Once it's no longer null, then you end up with differences in that the ??
operator would always return the first argument while the ?:
shorthand would only if the first argument was truthy, and that relies on how PHP would type-cast things to a boolean.
所以:
$a = false ?? 'f'; // false
$b = false ?: 'g'; // 'g'
然后会有 $a
等于 false
并且 $b
等于 'g'
.
would then have $a
be equal to false
and $b
equal to 'g'
.
这篇关于PHP三元运算符与空合并运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP三元运算符与空合并运算符


- 没有作曲家的 PSR4 自动加载 2022-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 带有通配符的 Laravel 验证器 2021-01-01
- Laravel 仓库 2022-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01
- SoapClient 设置自定义 HTTP Header 2021-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01