Null coalesce operator with casting

点点圈 提交于 2019-12-01 19:28:00

问题


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

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

to

$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;

I would think something like

$id = (int) $_GET['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

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


回答1:


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

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


来源:https://stackoverflow.com/questions/34967056/null-coalesce-operator-with-casting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!