2016-06-30 3 views
0

비슷한 오류가 며칠 전에 오류 처리에 대해 질문했습니다. 사람들은 수업에서 오류를 얻는 방법을 설명해주었습니다. 그리고 난 오류 이름을 만들고 __construct 섹션에서 확인하지만 여전히 여러 기능 여러 함수에서 클래스의 PHP 오류 처리

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 
    } 

그것은 작동하지만 문제 :

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; 
     } 

public function auth() 
{ 
//authentication goes here 

if... 
$errors[] = 'Error1'; 
else 
$errors[] = 'Error2'; 
etc... 

} 


} 

다른 파일 :

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

내 함수 auth()가 작동하고 echo를 반환하지만 마치 배열과 관련이 있습니다.

+0

를 호출 '$ test = new magic ('', '', '33'); '생성자가 예외를 던지고 인스턴스화 된 객체를 반환하지 않습니다. 그러므로'$ test'는 null이되고'$ test-> auth();'는 전혀 실행되지 않습니다. 예외는 아마도 사용자 입력 오류를 처리하는 최선의 방법이 아닙니다. – feeela

+0

@feeela 그럼 간단하다면 echo하는 것이 더 낫습니다. '; 각 함수에서? –

+0

아니요, 필요한 일부 인수가 예상과 다를 경우 생성자에서 [InvalidArgumentException'을 throw 할 수 있습니다 (http://php.net/InvalidArgumentException). 그러나'auth()'와 같은 메소드는 상태 코드를 반환해야합니다. 클래스 자체에 오류 텍스트를 저장하는 것은 좋은 생각이 아닙니다. 클라이언트에게 유용한 오류 메시지를 제시하고자 할 수 있기 때문입니다. 오류 코드를 리턴하면 다른 언어로 메시지를 표시 할 수 있습니다. 그러나 형식화 된 예외 (@GiamPy의 대답 참조)를 사용하는 것도 효과적입니다. – feeela

답변

1

내가하고있는 일은 불필요하다고 생각합니다.

생성자 매개 변수를 작성한 방법에 따라 기본값을 설정하지 않았으므로 해당 매개 변수가 필수이고 비어 있어서는 안됩니다.

여러 기능의 오류에 대해서는 사용자 정의 예외를 찾아 보시기 바랍니다. 특정 오류 (다른 동작이나 다른 유형의 오류를 적용해야하는 경우)에 대한 사용자 지정 예외를 만든 다음 Exception과 같이 예외를 잡습니다.

0

당신은 당신이 당신의 자신의 예외 클래스를 작성해야 배열로 예외에서 오류를 얻고 싶다면 :

class MagicException extends Exception 
{ 
    private $errors; 

    function __construct($message, array $errors, $code = 0, Exception $previous = null) 
    { 
     parent::__construct($message, $code, $previous); 
     $this->errors = $errors; 
    } 

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

사용법 :

try { 
    $errors = []; 

    // some code.. 
    $errors[] = 'Example error'; 

    if ($errors) { 
     throw new MagicException('Something went wrong', $errors); 
    } 
} catch (MagicException $e) { 
    // @todo: handle the exception 
    print_r($e->getErrors()); 
} 

출력 :

Array 
(
    [0] => Example error 
)