php ??,?:和?? =之间的区别
我并不完全清楚的事情,??
,?:和?? =
在PHP方面有何不同?
我知道?? =
仅在php7.4中添加。 我也知道??
是用于检查空值,但是?:
似乎还检查了空值,因此我不完全确定差异。
Something I'm not exactly clear on, how does ??
, ?:
, and ??=
differ in PHP?
I know ??=
was only added in PHP7.4.
I also know that ??
is for checking null values, but ?:
also seems to check for null values, so I'm not entirely sure of the difference.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
更多
发布评论
评论(1)
结合以前问题中已经做出的所有答案。使用
??
您检查存在而不是null
,?:您检查true/false
。与:
?? =
是> ??
的快捷方式,它的工作方式如=
或+= 也是,这意味着您可以缩短到
?:
是三元操作员的快捷方式,也是一个快捷方式:与:相同
:
您都可以描述为:第一个操作数是要检查的值,如果此操作数有用,请以默认为默认值(如果不是这样)。
您可以像这样将它们加入:
这意味着:如果您在帖子阵列中获取用户名,因为只是登录,很好,如果没有,请查看用户是否已经登录,并且在会话中是否已登录,如果是的,请考虑一下,如果没有,也许我们在cookie中有一个用户(在上次登录时检查了“记住我”复选框),如果这也失败了,那么,请将其留空。
当然,您也必须检查密码。 ;-)
编辑:我经常使用
?:
运算符,以确保我在变量中具有某些数据类型。有很多PHP函数可以将可能的字符串或数组回馈,但是如果发生某些错误,则false
。拥有空字符串或空数组的结果不再是错误的,而是更加一致。例如,scandir
应该回馈一个数组,但如果发生错误,则将false
归还。因此,您可以做到这一点:然后,即使
scandir
失败,$ files
也将永远是一个数组。好吧,那是一个空数组,但可能比以后对false
检查更好。实际上,我们已经付出了很少的努力。然后,您可以使用foreach
循环,而无需包装,则可以使用。如果scandir
失败,则数组为空,循环将无能为力。To combine all answers already made in former questions. With
??
you check for existence and not beingnull
, with?:
you check fortrue/false
.is the same as:
The
??=
is a shortcut for??
and it works like.=
or+=
as well, which means you can shortento
The
?:
is a shortcut for the ternary operator which is also a shortcut:is the same as:
is the same as:
You could both describe as: The first operand is the value to check, and if this one is useful, take it, if not, take the second as default.
You can concatenate them like this one:
Which means something like: If you get the username in the POST array because of just logging in, fine, take it, if not, see whether the user is already logged on and in the session, if yes, take it, if not, maybe we have a user in the Cookies (checked the "remember me" checkbox while last login), and if this fails also, well, then leave it empty.
Of course you have to check the password too. ;-)
Edit: I use the
?:
operator very often to ensure that I have a certain datatype in a variable. There are a lot PHP functions that give back maybe a string or an array if successful, butfalse
if some error occured. Instead of having false as result, having the empty string or empty array is more consistent. As example,scandir
should give back an array, but gives backfalse
if an error occures. So you can do this:Then
$files
will always be an array, even ifscandir
fails. Well, then it's an empty array, but maybe better than checking later againstfalse
. In fact, we already did it with very low effort. Then you can use aforeach
loop without some wrappingif
. Ifscandir
failed, the array is empty and the loop will just do nothing.