2016-06-27 4 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는'&&'가 결코 true로 평가 될 수 없다는 것을 안다. 왜냐하면 반환 값은'&&'의 값을 결정하는 것과 관련이 없으므로'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 
}