비슷한 오류가 며칠 전에 오류 처리에 대해 질문했습니다. 사람들은 수업에서 오류를 얻는 방법을 설명해주었습니다. 그리고 난 오류 이름을 만들고 __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를 반환하지만 마치 배열과 관련이 있습니다.
를 호출 '$ test = new magic ('', '', '33'); '생성자가 예외를 던지고 인스턴스화 된 객체를 반환하지 않습니다. 그러므로'$ test'는 null이되고'$ test-> auth();'는 전혀 실행되지 않습니다. 예외는 아마도 사용자 입력 오류를 처리하는 최선의 방법이 아닙니다. – feeela
@feeela 그럼 간단하다면 echo하는 것이 더 낫습니다. '; 각 함수에서? –
아니요, 필요한 일부 인수가 예상과 다를 경우 생성자에서 [InvalidArgumentException'을 throw 할 수 있습니다 (http://php.net/InvalidArgumentException). 그러나'auth()'와 같은 메소드는 상태 코드를 반환해야합니다. 클래스 자체에 오류 텍스트를 저장하는 것은 좋은 생각이 아닙니다. 클라이언트에게 유용한 오류 메시지를 제시하고자 할 수 있기 때문입니다. 오류 코드를 리턴하면 다른 언어로 메시지를 표시 할 수 있습니다. 그러나 형식화 된 예외 (@GiamPy의 대답 참조)를 사용하는 것도 효과적입니다. – feeela