在PHP7,一个新的功能,空合并运算符(??)已被引入。它被用来代替三元运算并与 isset()函数功能结合一起使用。如果它存在并且它不是空的,空合并运算符返回它的第一个操作数否则返回第二个操作数。
示例
<?php // fetch the value of $_GET[&aposuser&apos] and returns &aposnot passed&apos // if username is not passed $username = $_GET[&aposusername&apos] ?? &aposnot passed&apos print($username) print("<br/>") // Equivalent code using ternary operator $username = isset($_GET[&aposusername&apos]) ? $_GET[&aposusername&apos] : &aposnot passed&apos print($username) print("<br/>") // Chaining ?? operation $username = $_GET[&aposusername&apos] ?? $_POST[&aposusername&apos] ?? &aposnot passed&apos print($username) ?>
这将在浏览器产生输出以下结果-
not passed not passed not passed