2011-02-13 9 views
2

ねえ、 ここにあなたのための質問です。PHPクラスのエラー処理

私は、PHPでクラスのエラー処理を選択するのに多くの時間を費やしました。 AjaxをPHPの例では

は、私はこのようにそれを行うクラスの取り扱い:エラー処理のためのよりよい解決策はあり :

public function setError($msg) { 
    $this->errors[] = $msg; 
} 

public function isFailed() { 
    return (count($errors) > 0 ? true : false); // if errors > 0 the request is failed 
} 

public function getJsonResp() { 
    if($this->isFailed()) { 
     $resp = array('result' => false, 'message' => $this->errors[0]); 
    } else { 
     $resp = array('result' => true); 
     array_merge($resp, $this->success_data); // the success data is set later 
    } 
    return json_encode($resp); 
} 

// an example function for a execution of a method would be this 

public function switchMethod($method) { 
    switch($method) { 
     case 'create': 
      if(!isset($param1, $param2)) { 
       $this->setError('param1 or param2 not found'); 
      } else { 
       $this->createSomething(); 
      } 
      break; 
     default: 
      $this->setError('Method not found'); 
    } 
} 

をだから私はのためにAKSに何をしたいあなたを知ることができますか?

答えて

10

を参照してくださいには、例えば、あなたのエラーを処理するためにExceptionsを使用することです:

class Example extends BaseExample implements IExample 
{ 
    public function getExamples() 
    { 
     if($this->ExamplesReady === false) 
     { 
      throw new ExampleException("Examples are not ready."); 
     } 
    } 
} 

class ExampleException extends Exception{} 

があなたのクラス内で例外をスローし、そのクラスの外の例外をキャッチそれらを投げることは、私が通常行っていることです。

使用例:

$Example = new Example(); 
try 
{ 
    $Examples = $Example->getExamples(); 

    foreach($Examples as $Example) 
    { 
     //... 
    } 
}catch(ExampleException $e) 
{ 
    Registry::get("Output")->displayError("Unable to perform action",$e); 
} 

とあなたのdisplayErrorエラーに関する情報として$e->getMessage()を使用します。

+0

すべての機能でtry&catchを使用する必要がありますか? – 000

+0

いいえ、どこでエラーが発生する可能性がありますか、ほとんどの関数では、ゼロ除算例外のようなエラーを防ぐための単純なif文に頼ることができます。 – RobertPitt

+0

お返事ありがとうございます – 000

4

一般に、OOPでプログラミングするときは、「エラー」ハンドラとして例外を頻繁に使用します。

それはあなたの最善の策をOOPになるとhttp://php.net/exceptions