以下函数的PHP7方法是什么,它检查值是否设置并且等于特定值?
如果您看到其他任何改进空间,请告诉我们:
public function getResponseFormat($request)
{
$responseFormat = 'php';
if(isset($request['controller']['name']) && $request['controller']['name'] == 'email') {
if(isset($request['controller']['options']['responseFormat'])) {
$responseFormat = $request['controller']['options']['responseFormat'];
}
}
return $responseFormat;
}
答案 0 :(得分:2)
If you want to make use of the new NULL COALESCE operator, you can write the method like this:
public function getResponseFormat($request)
{
if ($request['controller']['name'] ?? null == 'email') {
return $request['controller']['options']['responseFormat'] ?? 'php';
}
return 'php';
}
$x ?? null
evaluates to null if $x is not set, and $x ?? 'php'
evaluates to 'php' if $x is not set.
You could also put everything in one line with an additional ternary operator ?:
to have a single return
but that would be at the cost of readability.