라이브러리
[PHP] Exception::__clone - 예외 복제
PHP Exception::__clone
PHP의 Exception 클래스는 `__clone` 매직 메소드를 지원하지 않습니다. 하지만, PHP 7.4 이상부터는 `__clone` 매직 메소드를 사용하여 Exception 클래스를 복사할 수 있습니다.
# 예제 1: Exception 클래스의 __clone 메소드
#hostingforum.kr
php
class CustomException extends Exception {
private $message;
public function __construct($message) {
$this->message = $message;
}
public function __clone() {
$this->message = "복사된 예외 메시지: " . $this->message;
}
}
try {
throw new CustomException("원본 예외 메시지");
} catch (CustomException $e) {
$e2 = clone $e;
echo $e->getMessage() . "
"; // 원본 예외 메시지
echo $e2->getMessage() . "
"; // 복사된 예외 메시지: 원본 예외 메시지
}
# 예제 2: Exception 클래스의 __clone 메소드 (PHP 7.4 이상)
#hostingforum.kr
php
class CustomException extends Exception {
private $message;
public function __construct($message) {
$this->message = $message;
}
public function __clone() {
$this->message = "복사된 예외 메시지: " . $this->message;
}
}
try {
throw new CustomException("원본 예외 메시지");
} catch (CustomException $e) {
$e2 = clone $e;
echo $e->getMessage() . "
"; // 원본 예외 메시지
echo $e2->getMessage() . "
"; // 복사된 예외 메시지: 원본 예외 메시지
}
# 예제 3: Exception 클래스의 __clone 메소드 (PHP 7.4 이하)
#hostingforum.kr
php
class CustomException extends Exception {
private $message;
public function __construct($message) {
$this->message = $message;
}
}
try {
throw new CustomException("원본 예외 메시지");
} catch (CustomException $e) {
$e2 = unserialize(serialize($e));
echo $e->getMessage() . "
"; // 원본 예외 메시지
echo $e2->getMessage() . "
"; // 원본 예외 메시지
}
# 예제 4: Exception 클래스의 __clone 메소드 (PHP 7.4 이상, PHP 7.4 이하)
#hostingforum.kr
php
class CustomException extends Exception {
private $message;
public function __construct($message) {
$this->message = $message;
}
public function __clone() {
$this->message = "복사된 예외 메시지: " . $this->message;
}
}
try {
throw new CustomException("원본 예외 메시지");
} catch (CustomException $e) {
if (version_compare(PHP_VERSION, '7.4.0', '>=')) {
$e2 = clone $e;
} else {
$e2 = unserialize(serialize($e));
}
echo $e->getMessage() . "
"; // 원본 예외 메시지
echo $e2->getMessage() . "
"; // 복사된 예외 메시지: 원본 예외 메시지
}
결론
PHP의 Exception 클래스는 `__clone` 매직 메소드를 지원하지 않습니다. 하지만, PHP 7.4 이상부터는 `__clone` 매직 메소드를 사용하여 Exception 클래스를 복사할 수 있습니다. PHP 7.4 이하의 경우, `unserialize` 함수를 사용하여 Exception 객체를 복사할 수 있습니다.
-
- 나우호스팅 @pcs8404
-
호스팅포럼 화이팅!
댓글목록
등록된 댓글이 없습니다.