空合并运算符,带铸造 [英] Null coalesce operator with casting

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

问题描述

我已经升级到PHP 7,并开始使用null合并运算符转换诸如此类的

I have upgraded to PHP 7 and started using the null coalesce operator to convert things like

$email = isset($_SESSION['email']) ? $_SESSION['email'] : '';

$email = $_SESSION['email'] ?? '';

但是如果我也进行投射,我不知道该怎么做.例如,旧语句的

but I can't figure out how to do this if I am casting as well. For example, the for the old statement

$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;

我会想像

$id = (int) $_GET['id'] ?? 0;

应该可以工作,但是从某种意义上讲,如果未设置$_GET['id'],则$id会解析为0,但我会收到通知

should work, but it doesn't appear to in the sense that, if $_GET['id'] is not set, $id resolves to 0 but I get the Notice

注意:未定义的索引:第2行中test.php中的ID

Notice: Undefined index: id in test.php on line 2

推荐答案

(int)强制转换优先于??运算符,因此请使用方括号:

The (int) cast gets precedence over the ?? operator, so use brackets:

$id = (int) ($_GET['id'] ?? 0);

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

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