PHP7.0 新特性 null合并运算符

新的项目使用PHP7.0版本的,有一个新特性比较好,这里来分享以下,那就是原来的Isset方法, 先看代码:

public function testFunction($testData)
{
return $data =
[
‘_id’ => isset($testData[‘id’]) ? $testData[‘id’] : “”,
‘anchorId’ => isset($testData[‘anchorId’]) ? $testData[‘anchorId’] : “”,
‘title’ => isset($testData[‘title’]) ? $testData[‘title’] : “”,
‘describe’ => isset($testData[‘describe’]) ? $testData[‘describe’] : “”,
‘tags’ => isset($testData[‘tags’]) ? $testData[‘tags’] : [],
‘coverUrl’ => isset($testData[‘coverUrl’]) ? $testData[‘coverUrl’] : “”,
‘startTime’ => isset($testData[‘startTime’]) ? $testData[‘startTime’] : “”,
‘endTime’ => isset($testData[‘endTime’]) ? $testData[‘endTime’] : “”,
‘duration’ => isset($testData[‘duration’]) ? $testData[‘duration’] : “”,
‘watchNum’ => isset($testData[‘watchNum’]) ? $testData[‘watchNum’] : 0,
‘onlineNum’ => isset($testData[‘onlineNum’]) ? $testData[‘onlineNum’] : 0,
‘duration’ => isset($testData[‘duration’]) ? $testData[‘duration’] : “”,
‘screenType’ => isset($testData[‘screenType’]) ? $testData[‘screenType’] : 2
‘status’ => isset($testData[‘status’]) ? $testData[‘status’] : 2
‘geo’ => isset($testData[‘geo’]) ? $testData[‘geo’] : [],
‘location’ => isset($testData[‘location’]) ? $testData[‘location’] : [],
‘clientIp’ => isset($testData[‘clientIp’]) ? $testData[‘clientIp’] : ”,
‘createTime’ => isset($testData[‘createTime’]) ? $testData[‘createTime’] : time(),
‘createTime’ => time(),
]
);
}

这里我们需要先判断是否存在,再去赋值,看起来比较繁琐,php7中新的 ?? 代替isset功能,修改后的代码:

public function testFunction($testData)
{
return $this->insert(
[
‘_id’ => $testData[‘id’] ?? “”,
‘anchorId’ => $testData[‘anchorId’] ?? “”,
‘title’ => $testData[‘title’] ?? “”,
‘describe’ => $testData[‘describe’] ?? “”,
‘tags’ => $testData[‘tags’] ?? [],
‘coverUrl’ => $testData[‘coverUrl’] ?? “”,
‘startTime’ => $testData[‘startTime’] ?? “”,
‘endTime’ => $testData[‘endTime’] ?? “”,
‘duration’ => $testData[‘duration’] ?? “”,
‘watchNum’ => $testData[‘watchNum’] ?? 0,
‘onlineNum’ => testData[‘onlineNum’] ?? 0,
‘duration’ => $testData[‘duration’] ?? “”,
‘screenType’ => $testData[‘screenType’] ?? 2,
‘status’ => $testData[‘status’] ?? 2
‘geo’ => $testData[‘geo’] ?? [],
‘location’ => $testData[‘location’] ?? [],
‘clientIp’ => $testData[‘clientIp’] ?? ”,
‘createTime’ => $testData[‘createTime’] ?? time(),
‘createTime’ => time(),
]
);
}

看起来是不是精简了很多。

Be the First to comment.

猜你喜欢

转载自blog.csdn.net/wccczxm/article/details/89379133