PHP NULL coalescing operator
PHP NULL coalescing operator
PHP 7 The newly added NULL coalescing operator (??) is a shortcut for performing the ternary operation detected by isset().
The NULL coalescing operator will determine whether the variable exists and the value is not NULL. If so, it will return its own value, otherwise it will return its second operand.
We used to write the ternary operator like this:
$site = isset($_GET['site']) ? $_GET['site'] : 'php Chinese website ';
Now we can write directly like this:
$site = $_GET['site'] ?? 'php Chinese website';
Example
<?php // 获取 $_GET['site'] 的值,如果不存在返回 'php中文网' $site = $_GET['site'] ?? 'php中文网'; print($site); echo "<br/>"; print(PHP_EOL); // PHP_EOL 为换行符 // 以上代码等价于 $site = isset($_GET['site']) ? $_GET['site'] : 'php中文网'; print($site); echo "<br/>"; print(PHP_EOL); // ?? 链 $site = $_GET['site'] ?? $_POST['site'] ?? 'php中文网'; print($site); ?>
The execution output of the above program is:
php中文网
php中文网
php中文网
php中文网
php中文网