在這里,你可以了解更多有關(guān) PHP7 的新特性。
在 PHP7 中,引入了一個(gè)新的功能,即空合并運(yùn)算符(??)。由于在 PHP7 項(xiàng)目中存在大量同時(shí)使用三元表達(dá)式和 isset() 的情況,因此新增的空合并運(yùn)算符可以用來取代三元運(yùn)算與 isset () 函數(shù),如果變量是存在的并且不為 null ,則空合并運(yùn)算符將返回它的第一個(gè)操作數(shù);否則將返回其第二個(gè)操作數(shù)。
在舊版的PHP中:isset($_GET[‘id']) ? $_GET[id] : err;而新版的寫法為:$_GET['id'] ?? 'err';
具體的使用參考:
之前版本寫法:
$info = isset($_GET['email']) ? $_GET['email'] : 'noemail';
PHP7版本的寫法:
$info = $_GET['email'] ?? 'noemail';
還可以寫成這種形式:
$info = $_GET['email'] ?? $_POST['email'] ?? 'noemail';
<?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);
?>
它產(chǎn)生以下瀏覽器輸出 :
not passed
not passed
not passed
更多建議: