PHP7空合并運算符如何使用

2020-12-25 19:40 更新

在這里,你可以了解更多有關 PHP7 的新特性。

在 PHP7 中,引入了一個新的功能,即空合并運算符(??)。由于在 PHP7 項目中存在大量同時使用三元表達式和 isset() 的情況,因此新增的空合并運算符可以用來取代三元運算與 isset () 函數(shù),如果變量是存在的并且不為 null ,則空合并運算符將返回它的第一個操作數(shù);否則將返回其第二個操作數(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);
?>

它產生以下瀏覽器輸出 :

not passed
not passed
not passed


以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號