-4

新しい PHP バージョンである PHP 7 のリリースに伴い、新しい機能が導入されました。これらの新機能の中には、私がよく知らない演算子があります。Null coalesce operator。_

この演算子とは何ですか? また、適切な使用例は何ですか?

4

3 に答える 3

4

nullの可能性がある変数を初期化するために使用できます

?? 演算子は null 合体演算子と呼ばれます。オペランドが null でない場合は左側のオペランドを返します。それ以外の場合は、右側のオペランドを返します。

ソース: https://msdn.microsoft.com/nl-nl/library/ms173224.aspx

(言語に依存しない)

使用事例

あなたは書ける

$rabbits;

$rabbits = count($somearray);

if ($rabbits == null) {
    $rabbits = 0;
}

短い表記を使用できます

$rabbits = $rabbits ?? 0;
于 2015-11-12T07:30:33.140 に答える
1

According to the PHP Manual:

The null coalesce operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

// Fetches the value of $_GET['user'] and returns 'nobody'
// if it does not exist.
$username = $_GET['user'] ?? 'nobody';
// This is equivalent to:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';

// Coalesces can be chained: this will return the first
// defined value out of $_GET['user'], $_POST['user'], and
// 'nobody'.
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
于 2015-11-12T07:53:27.203 に答える