在PHP7,一个新的功能,空合并运算符(??)已被引入。它被用来代替三元运算并与 isset()函数功能结合一起使用。如果它存在并且它不是空的,空合并运算符返回它的第一个操作数;否则返回第二个操作数。
示例
<?php
// fetch the value of $_GET['user'] and returns 'not passed'
// if username is not passed
$username = $_GET['username'] ?? 'not passed';
print($username);
print("<br/>");
// Equivalent code using ternary operator
$username = isset($_GET['username']) ? $_GET['username'] : 'not passed';
print($username);
print("<br/>");
// Chaining ?? operation
$username = $_GET['username'] ?? $_POST['username'] ?? 'not passed';
print($username);
?>
这将在浏览器产生输出以下结果-
not passed not passed not passed
本文介绍了PHP7中新增的空合并运算符(??),它用于替代三元运算符并与isset()函数结合使用,实现对变量值的安全获取。通过示例代码展示了其用法及与三元运算符的等效转换。
660

被折叠的 条评论
为什么被折叠?



