PHP 7 Null合并运算符
PHP 7 Null合并运算符
在PHP 7中,增加了一个新特性,null合并运算符,它用于与isset()函数一起替换三元操作。Null合并运算符返回其第一个操作数(如果存在并且不是Null);否则返回第二个操作数。
例子
<?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