(??=) 双问号和等号,那个运算符有什么作用? [英] (??=) Double question mark and an equal sign, what does that operator do?

查看:114
本文介绍了(??=) 双问号和等号,那个运算符有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一次我偶然发现了带有运算符 ??= 的 php7 代码.我试图搜索,它清楚地做了什么,但无法轻松找到.我试着读出php操作符,甚至大多数官方资源都有所有操作符的描述,甚至像.=+=这样的复合操作符,但没有对??=

Once I stumbled with php7 code with operator ??=. I tried to search, what it clearly does, but could not find easily. I tried to read out the php operators and even most official resources have all operators description and even compound operators like .=, +=, but there are no description for ??=

例如,PHP Operators 将所有运算符的描述保留为直接形式(., +),作为复合(.=, +=),但是没有??=,正因为如此,我首先感到困惑,并认为这完全是另一回事.问题简单明了,但整个案例有点混乱,这就是为什么我试图帮助像我这样的其他php初学者

For example, PHP Operators keeps descriptions of all operators, as straight form (., +), as compound (.=, +=), but there is no ??=, and because of that I firstly was confused and thought it's something totally another. The issue is simple and obvious, but the whole case is a bit confusing, that's why I try to help other php-beginners like me

推荐答案

所以最终我决定自己编写代码并观察它的工作原理和作用.

So eventually I decided to wright code and watch by myself, how it works and what it does.

在 PHP7.0 中添加了 空合并运算符:

In PHP7.0 was added the Null Coalescing operator:

$username = $_GET['username'] ?? 'not passed'; 

我们的 $username 将有 $_GET['username'] 值 - 如果它存在且不为空,否则 $username 将获得未通过"字符串.但有时您可能会遇到这种情况,当您需要检查变量本身是否存在和不可为空时:

Our $username will have $_GET['username'] value - if it exists and not null, otherwise $username will get 'not passed' string. But sometimes you can have a situation, when you need to check for existence and not-nullability the variable itself:

$first_test = $first_test ?? 'not started';

在这种情况下,您可以使用空合并运算符的复合版本 - '??=':

And in this situation you can use a compound version of null coalescing operator - '??=':

$first_test ??= 'not started';

就是这样,只是'??'的复合版本对于您检查自身变量的情况.

That's it, just compound version of '??' for the cases, where you check the itself variable.

这篇关于(??=) 双问号和等号,那个运算符有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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