What is this new null coalescing assignment ??= operator in PHP 7.4

醉酒当歌 提交于 2020-02-03 05:19:20

问题


I've just seen a video about upcoming PHP 7.4 features and saw this ??= new operator. I already know the ?? operator. How's this different?


回答1:


From the docs:

Coalesce equal or ??=operator is an assignment operator. If the left parameter is null, assigns the value of the right paramater to the left one. If the value is not null, nothing is made.

Example:

// The folloving lines are doing the same
$this->request->data['comments']['user_id'] = $this->request->data['comments']['user_id'] ?? 'value';
// Instead of repeating variables with long names, the equal coalesce operator is used
$this->request->data['comments']['user_id'] ??= 'value';

So it's basically just a shorthand to assign a value if it hasn't been assigned before.




回答2:


The null coalescing assignment operator is a shorthand way of assigning the result of the null coalescing operator.

An example from the official release notes:

$array['key'] ??= computeDefault();
// is roughly equivalent to
if (!isset($array['key'])) {
    $array['key'] = computeDefault();
}



回答3:


In PHP 7 this was originally released, allowing a developer to simplify an isset() check combined with a ternary operator. For example, before PHP 7, we might have this code:

$data['username'] = (isset($data['username']) ? $data['username'] : 'guest');

When PHP 7 was released, we got the ability to instead write this as:

$data['username'] = $data['username'] ?? 'guest';

Now, however, when PHP 7.4 gets released, this can be simplified even further into:

$data['username'] ??= 'guest';

One case where this doesn't work is if you're looking to assign a value to a different variable, so you'd be unable to use this new option. As such, while this is welcomed there might be a few limited use cases.




回答4:


Example Docs:

$array['key'] ??= computeDefault();
// is roughly equivalent to
if (!isset($array['key'])) {
    $array['key'] = computeDefault();
}


来源:https://stackoverflow.com/questions/59102708/what-is-this-new-null-coalescing-assignment-operator-in-php-7-4

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!