返回false,而不是引发异常


Return false instead throw exception

我有这个函数:

public static function get($action, $param = null) {
    $options = array(
        'http' => array(
            'header'  => "Content-type: application/x-www-form-urlencoded'r'n",
            'method'  => "GET"
        )
    );
    $context  = stream_context_create($options);
    $params = '';
    foreach($param as $key => $value)
        $params .= $key . '=' . $value . '&';
    trim($params, '&');
    $result = file_get_contents(self::$url . $action . '?' . $params, false, $context);
    return json_decode($result, true);
}

问题是:当我向file_get_contents提供错误的url时,它会抛出错误(Exception)。但是,我想返回false而不抛出错误。我该怎么做?

在这种情况下,您应该使用try {} catch {}来捕获异常并采取措施。

try {
   $result = file_get_contents(self::$url . $action . '?' . $params, false, $context);
} catch ('Exception $e) {
 return false;
}

您可以简单地用try-catch块包围它:

公共静态函数get($action,$param=null){$options=数组("http"=>阵列('header'=>"内容类型:application/x-www-form-urlencoded''r''n","方法"=>"获取"));$context=stream_context_create($options);$params=";foreach($param作为$key=>$value)$params.=$键。'='$值。'&';trim($params,'&');尝试{$result=file_get_contents(self::$url.$action.'?'.$params,false,$context);返回json_decode($result,true);}catch(异常$exc){return false;}}

try使PHP异常感知可以说:如果在try块内抛出异常,PHP将执行catch块,这里$exc将包含抛出异常的详细信息。