라이브러리

[PHP] Throwable::__toString - 던져진 객체의 문자열 표현을 가져옵니다.




PHP 에서 `Throwable::__toString()` 메소드는 Throwable 인터페이스를 구현한 클래스의 오류 메시지를 문자열로 반환하는 메소드입니다. 이 메소드는 오류 메시지를 문자열로 변환하기 위해 사용됩니다.

Throwable::__toString() 메소드


`Throwable::__toString()` 메소드는 오류 메시지를 문자열로 반환하는 메소드입니다. 이 메소드는 오류 메시지를 문자열로 변환하기 위해 사용됩니다.

# 예제 1: 기본 사용법


#hostingforum.kr
php

class CustomException extends Exception {

    public function __toString() {

        return '커스텀 오류 메시지';

    }

}



try {

    throw new CustomException();

} catch (Exception $e) {

    echo $e->__toString(); // 커스텀 오류 메시지

}



# 예제 2: 오류 메시지에 변수 포함


#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 (Exception $e) {

    echo $e->__toString(); // 커스텀 오류 메시지: 오류 메시지

}



# 예제 3: 오류 메시지에 오류 코드 포함


#hostingforum.kr
php

class CustomException extends Exception {

    private $code;



    public function __construct($message, $code) {

        $this->code = $code;

        parent::__construct($message);

    }



    public function __toString() {

        return '커스텀 오류 메시지 (' . $this->code . '): ' . parent::getMessage();

    }

}



try {

    throw new CustomException('오류 메시지', 500);

} catch (Exception $e) {

    echo $e->__toString(); // 커스텀 오류 메시지 (500): 오류 메시지

}



결론


`Throwable::__toString()` 메소드는 오류 메시지를 문자열로 반환하는 메소드입니다. 이 메소드는 오류 메시지를 문자열로 변환하기 위해 사용됩니다. 예제를 통해 오류 메시지에 변수와 오류 코드를 포함하는 방법을 살펴보았습니다.
  • profile_image
    나우호스팅 @pcs8404 

    호스팅포럼 화이팅!

    댓글목록

    등록된 댓글이 없습니다.

  • 전체 10,077건 / 151 페이지

검색

게시물 검색