gpt4 book ai didi

PHP Elvis 运算符与空合并运算符

转载 作者:IT老高 更新时间:2023-10-28 11:38:22 28 4
gpt4 key购买 nike

谁能解释ternary operator shorthand 之间的区别? (?:) 和 null coalescing operator (??) 在 PHP 中?

他们什么时候表现不同,什么时候表现相同(如果这种情况发生的话)?

$a ?: $b

VS.

$a ?? $b

最佳答案

当您的第一个参数为 null 时,它们基本相同,只是当您有 undefined variable 时,null 合并不会输出 E_NOTICEPHP 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 Elvis 运算符与空合并运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34571330/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com