2016-05-01 8 views
0

をスローリターン偽:代わりに、私はこの機能を持っている例外

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を提供する場合、それはエラー(例外)を投げます。 しかし、私はスローエラーなしで代わりにfalseを返したいと思います。 どうすればいいですか?

+0

その行内でcatchブロックを試してください – ashish

答えて

1

例外をキャッチしてこの場合は何かを行うには、try {} catch {}を使用する必要があります。例外はtryブロック内をスローされた場合、PHPを実行します:

 

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, '&'); 

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

tryは、PHPの例外を意識した1が言うことができます:あなたはtry-catchブロックとそれを単に囲むことができ

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

catchブロック、ここでは$excにはスローされた例外の詳細が含まれます。

関連する問題