PHP NULL 合併運(yùn)算子

PHP 7 新增加的 NULL 合併運(yùn)算子(??)是用來執(zhí)行isset()偵測的三元運(yùn)算的捷徑。

NULL 合併運(yùn)算子會判斷變數(shù)是否存在且值不為NULL,如果是,它就會傳回自身的值,否則傳回它的第二個(gè)運(yùn)算元。

以前我們這樣寫三元運(yùn)算子:

$site?=?isset($_GET['site'])???$_GET['site']?:?'php中文網(wǎng)';

現(xiàn)在我們可以直接這樣寫:

$site?=?$_GET['site']????'php中文網(wǎng)';

#實(shí)例

<?php
// 獲取 $_GET['site'] 的值,如果不存在返回 'php中文網(wǎng)'
$site = $_GET['site'] ?? 'php中文網(wǎng)';
print($site);
echo "<br/>";
print(PHP_EOL); // PHP_EOL 為換行符
// 以上代碼等價(jià)于
$site = isset($_GET['site']) ? $_GET['site'] : 'php中文網(wǎng)';
print($site);
echo "<br/>";
print(PHP_EOL);
// ?? 鏈
$site = $_GET['site'] ?? $_POST['site'] ?? 'php中文網(wǎng)';
print($site);
?>

以上程式執(zhí)行輸出結(jié)果為:

php中文網(wǎng)
php中文網(wǎng)
php中文網(wǎng)