
__toString() 메서드를 오버라이딩하는 방법은 다음과 같습니다.
1. Exception 클래스를 상속하는 자식 클래스를 생성합니다.
2. 자식 클래스에서 __toString() 메서드를 오버라이딩합니다.
3. 오버라이딩한 __toString() 메서드에서 원하는 문자열을 반환합니다.
예를 들어, 다음과 같이 자식 클래스를 생성하고 __toString() 메서드를 오버라이딩할 수 있습니다.
#hostingforum.kr
php
class CustomException extends Exception {
private $message;
public function __construct($message) {
$this->message = $message;
}
public function __toString() {
return "에러 메시지: " . $this->message;
}
}
try {
throw new CustomException("테스트 에러 메시지");
} catch (CustomException $e) {
echo $e . "n";
}
이 예제에서는 CustomException 클래스를 생성하고 __toString() 메서드를 오버라이딩하여 원하는 문자열을 반환합니다.
2025-04-28 07:16