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

后端 未结 5 1636
渐次进展
渐次进展 2020-12-06 16:51

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

5条回答
  •  渐次进展
    2020-12-06 17:15

    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.

提交回复
热议问题