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