我应该检查一个键是否存在,然后得到它还是只得到它(当我需要得到它,而不是检查它的设置)?
什么更可靠?更安全?更快?
示例:
1) PHP (https://github.com/nicolasff/phpredis)
if ($redis->exists('key'))
echo $redis->get('key');
// VS
if ($value = $redis->get('key'))
echo $value;2) phalcon (http://docs.phalconphp.com/pt/latest/reference/cookies.html)
if ($this->cookies->has('remember-me'))
echo $this->cookies->get('remember-me')->getValue()
// VS
if ($value = $this->cookies->get('remember-me')->getValue())
echo $value;谢谢!
发布于 2014-09-19 13:39:23
我对这个问题的解释是:
我不喜欢写像这样的东西
if ($value = $redis->get('key'))
echo $value;这使得代码不清楚。
此外,为什么检查变量是否存在如此重要?,因为它简化了控制流.
让我们考虑一下,您正在从服务中获取一些数据,以便在页面上呈现它。您可以使用多个if编写低质量的代码,但也可以尝试如下所示:
offerServiceImpl.php
class offerServiceImpl implements offerService {
//... (some methods)
/**
* @param int $offerId
* @return Offer
* @throws InvalidArgumentException
* @throws RuntimeException
*/
public function getOffer($offerId)
{
if (!$offerId || !is_numeric($offerId)) {
throw new InvalidArgumentException("Invalid offer id: " . $offerId);
}
$offer = $this->offerDao->get($offerId);
if (!$offer) {
//could be your own exception class
throw new RuntimeException("Could not found offer " . $offerId);
} else {
return $offer;
}
}
}offersControler.php
class offersController extends AbstractController{
public function index($id){
//... some code
try{
$offer = $this->offerService->getOffer($id);
} catch (InvalidArgumentException $ex) {
//log error, perform redirect to error 500
} catch (RuntimeException $ex){
//log another error, perform redirect to error 404
} catch (Exception $ex){
//log error, perform redirect to error 500
}
}
}https://stackoverflow.com/questions/25934473
复制相似问题