2016-06-27 12 views
0

私はまだPHPとOOPで遊んでいます。しかし、クラスからエラーを取り戻す方法を理解していない。PHPクラスでのエラー処理

インデックスファイル

include 'class.php'; 
$test = new magic('', '', '33'); 
$test->getfullname(); 
foreach ($test->get_errors() as $error) { 
    echo $error . '<br>'; 
} 

クラス:

class magic 
{ 

    private $name; 
    private $surname; 
    private $age; 
    private $errors = array(); 

    function __construct($name, $surname, $age) 
    { 
     $this->name = $name; 
     $this->surname = $surname; 
     $this->age = $age; 
    } 

    public function get_errors() 
    { 
     return $this->errors; 
    } 

    public function getname() 
    { 
     if (!empty($this->name)) { 
      return true; 
     } else { 

      array_push($this->errors, 'Please check name'); 
      return false; 
     } 
    } 

    public function getsurname() 
    { 
     if (!empty($this->surname)) { 
      return true; 
     } else { 

      array_push($this->errors, 'Please check surname'); 
      return false; 
     } 
    } 

    public function getfullname() 
    { 
     if (($this->getname()) && ($this->getsurname())) { 
      echo $this->name . ' ' . $this->surname; 
     } 
    } 

} 

名または姓が空の時に私の質問は、なぜ、名前または姓を確認したが、両方が空のときに戻ってください戻っています最初だけ?どのようにPHPクラスでこれらの型エラーをキャンドルすると、それを行うためのベストプラクティスは何ですか? このシナリオではtry/catch例外を使用することはできません。

+2

短絡評価。 'getName()'がfalseを返した場合、PHPはあなたの '&&'が真に評価されないことを知っているので、戻り値は '&&'の値を決定するのに無関係であるため 'getSurname'を呼び出すことはありません。 –

+0

@ MarcBしかし、一般的にはこれはかなり正しいですか? –

+0

http://php.net/manual/en/language.operators.logical.php。例の最初の4行に注意してください。 –

答えて

2

私は、コンストラクタでエラーを処理し、例外をスロー示唆しています。

class magic 
{ 

    /** 
    * @param string $name 
    * @param string $surname 
    * @param int $age 
    * @throws Exception 
    */ 
    public function __construct($name, $surname, $age) 
    { 
     $errors = []; 

     if (empty($name)) { 
      $errors[] = 'Name is required.'; 
     } 

     if (empty($surname)) { 
      $errors[] = 'Surname is required.'; 
     } 

     if (!empty($errors)) { 
      throw new Exception(implode('<br />', $errors)); 
     } 

     $this->name = $name; 
     $this->surname = $surname; 
     $this->age = $age; 
    } 

    public function printFullname() 
    { 
     echo $this->name . ' ' . $this->surname; 
    } 

} 

クライアント:

include 'class.php'; 

try { 
    $test = new magic('', '', '33'); 
    $test->printFullname(); 
} catch (Exception $exc) { 
    echo $exc->getMessage(); //error messages 
}