在尝试获取数组/集合值之前,我应该检查它是否存在?

时间:2014-09-19 12:56:59

标签: php

我应该检查一个密钥是否存在然后得到它或者只是得到它(当我需要它时,不检查它是否设置)?

什么更可靠?更安全吗?快?

示例:

1)PHP redis(https://github.com/nicolasff/phpredis

if ($redis->exists('key'))
    echo $redis->get('key');
// VS
if ($value = $redis->get('key'))
    echo $value;

2)PHP phalcon cookies(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;

谢谢!

1 个答案:

答案 0 :(得分:0)

我对这个问题的解释是:

我不喜欢写

之类的东西
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
        }
    }
}