PHP NULL Coalescing Operator
The NULL coalescing operator (??) newly added in PHP 7 is a shortcut for ternary operations that perform isset() checks.
The NULL coalescing operator checks whether a variable exists and is not NULL; if so, it returns its own value, otherwise it returns its second operand.
Previously we wrote the ternary operator like this:
$site = isset($_GET['site']) ? $_GET['site'] : 'Example';
Now we can write it directly like this:
$site = $_GET['site'] ?? 'Example';
Example
<?php // 获取 $_GET['site'] 的值,如果不存在返回 'Example' $site = $_GET['site'] ?? 'Example'; print($site); print(PHP_EOL); // PHP_EOL 为换行符 // 以上代码等价于 $site = isset($_GET['site']) ? $_GET['site'] : 'Example'; print($site); print(PHP_EOL); // ?? 链 $site = $_GET['site'] ?? $_POST['site'] ?? 'Example'; print($site); ?>
The output of the above program execution is:
Example Example Example
Other Extensions