Php7-coalescing-operator
提供:Dev Guides
PHP 7-ヌル合体演算子
PHP 7では、* null合体演算子(??)という新機能が導入されました。 isset()関数とともに *ternary 操作を置き換えるために使用されます。 Null 合体演算子は、最初のオペランドが存在し、NULLでない場合、それを返します。それ以外の場合は、2番目のオペランドを返します。
例
<?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