在php中,我发现自己经常这样做:
$res->getBody()->getContents();
但是如果body返回null,则下一次调用将引发致命错误。
在雄辩中,这可能更糟。
是否有更清洁的解决方案,而不是
if ($res and $res->getBody()) {
return $res->getBody()->getContent();
} else {
return null;
}
您可以使用三元运算符(例如,在Laravel中始终使用):
return $res and $res->getBody() ? $res->getBody()->getContents() : null;
或者在您想返回相同的想法的情况下,Elvis operator
:
return $res->getBody()?: $something_else ; // this check only if the getbody() call return null, and if not, return what that call has returns, otherwise $something_else
请注意,有时可以使用默认运算符,如下所示:
return $res->getBody() ?? $default_or_whatever; // if getBody returns something evaluated as false, it will return the $default_or_whatever
// same thing as return $res->getBody() ? $res->getBody() : $default_or_whatever
// and return $res->getBody() ?: $default_or_whatever
您对此方法有何看法:
function valueOrNull(callable $closure){
try{
return $closure();
} catch (\Throwable $e){
return null;
}
}
//$rv always null or return value never matter what
$rv = valueOrNull(fn()=> $res->getBody()->getContents()->getFirstItem()->getName());;