Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

PHP 7.4 introduced Null coalescing assignment operator here's the RFC .

(PHP 7.4引入了Null合并赋值运算符,这里是RFC 。)

Here's the example for it:

(这是它的示例:)

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

As this seems reducing code repetition it's actually doing the opposite IMO, because in real life I would do this:

(由于这似乎减少了代码重复,实际上是在执行相反的IMO,因为在现实生活中,我会这样做:)

$id=$this->request->data['comments']['user_id'] ?? 'value';

Here I'm taking an advantage of copy-on-write policy in PHP.

(在这里,我利用了PHP中的写时复制策略 。)

Now I know that this will not change the data in the array ( which is good ) because if we do this:

(现在,我知道这不会更改数组中的数据(这是很好的),因为如果执行此操作:)

$this->request->data['comments']['user_id'] ??= 'value';

We will end up doing this :

(我们最终会这样做:)

$id = $this->request->data['comments']['user_id'];

Or this:

(或这个:)

echo $this->request->data['comments']['user_id'];

Which will lead to code repetition and also decreasing readability

(这将导致代码重复并降低可读性)

So again how is null coalescing assignment operator really useful?

(那么,空合并赋值运算符真的有用吗?)

  ask by FatalError translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
577 views
Welcome To Ask or Share your Answers For Others

1 Answer

In PHP 7 this was originally released, allowing a developer to simplify an isset() check combined with a ternary operator.

(它最初是在PHP 7中发布的,它允许开发人员简化与三元运算符结合的isset()检查。)

For example, before PHP 7, we might have this code:

(例如,在PHP 7之前,我们可能有以下代码:)

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

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

(当PHP 7发布时,我们可以改为这样写:)

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

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

(但是,现在,当发布PHP 7.4时,可以进一步简化为:)

$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.

(因此,尽管这很受欢迎,但可能会有一些有限的用例。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...