использование в массиве оператора слияния PHP - PullRequest
0 голосов
/ 16 ноября 2018

Я использую нуль-оператор объединения PHP, описанный http://php.net/manual/en/migration70.new-features.php.

Null coalescing operator ¶
The null coalescing 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.

<?php
// 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';

// Coalescing can be chained: this will return the first
// defined value out of $_GET['user'], $_POST['user'], and
// 'nobody'.
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
?>

Я заметил, что следующее не дает ожидаемых результатов, которые должны были добавить новый индекс phone к $params, чейзначение по умолчанию.

$params=['address'=>'123 main street'];
$params['phone']??'default';

Почему бы и нет?

1 Ответ

0 голосов
/ 16 ноября 2018

Вы ничего не добавляете к параметрам.Данный код просто генерирует неиспользуемое возвращаемое значение:

$params['phone'] ?? 'default'; // returns phone number or "default", but is unused

Таким образом, вам все равно придется его установить:

$params['phone'] = $params['phone'] ?? 'default';
...