PHP 三元运算符与空合并运算符 [英] PHP ternary operator vs null coalescing operator

查看:41
本文介绍了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 三元运算符与空合并运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆