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

查看:111
本文介绍了PHP三元运算符vs空合并运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释PHP中的三元运算符速记(?:)和空合并运算符(??)之间的区别吗?

它们什么时候表现不同并且何时以相同的方式出现(即使发生这种情况)?

$a ?: $b

VS.

$a ?? $b

解决方案

当您的第一个参数为null时,它们基本相同,只是当您有未定义的变量时,空合并不会输出E_NOTICE. PHP 7.0迁移文档这样说:

已添加空合并运算符(??)作为语法糖 对于需要结合使用三元数的常见情况 isset().如果存在且不为NULL,则返回其第一个操作数;否则,返回第一个操作数. 否则,它将返回其第二个操作数.

下面是一些示例代码来演示这一点:

<?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.一旦它不再为null,则最终会出现差异,因为??运算符将始终返回第一个参数,而?:速记符仅在第一个参数为true时才返回,并且这取决于 解决方案

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:

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 "\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";

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.

Execute the code: https://3v4l.org/McavC

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.

So:

$a = false ?? 'f'; // false
$b = false ?: 'g'; // 'g'

would then have $a be equal to false and $b equal to 'g'.

这篇关于PHP三元运算符vs空合并运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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