PHP 유형 힌트에서 "catchable fatal error"를 어떻게 잡을 수 있나요?
-
20-09-2019 - |
문제
내 수업 중 하나에 PHP5의 유형 힌트를 구현하려고 합니다.
class ClassA {
public function method_a (ClassB $b)
{}
}
class ClassB {}
class ClassWrong{}
올바른 사용법:
$a = new ClassA;
$a->method_a(new ClassB);
오류 발생:
$a = new ClassA;
$a->method_a(new ClassWrong);
포착 가능한 치명적인 오류:ClassA::method_a()에 전달된 인수 1은 ClassB의 인스턴스, ClassWrong의 인스턴스여야 합니다.
해당 오류("catchable"이라고 표시되어 있으므로)를 잡을 수 있는지 알 수 있습니까?그렇다면 어떻게?
감사합니다.
해결책
업데이트:이것은 PHP 7에서는 더 이상 잡을 수 있는 치명적인 오류가 아닙니다.대신 "예외"가 발생합니다.다음에서 파생되지 않은 "예외"(공포 인용문) 예외 하지만 오류;그것은 아직도 던질 수 있는 일반적인 try-catch 블록으로 처리할 수 있습니다.보다 https://wiki.php.net/rfc/throwable-interface
예:
<?php
class ClassA {
public function method_a (ClassB $b) { echo 'method_a: ', get_class($b), PHP_EOL; }
}
class ClassWrong{}
class ClassB{}
class ClassC extends ClassB {}
foreach( array('ClassA', 'ClassWrong', 'ClassB', 'ClassC') as $cn ) {
try{
$a = new ClassA;
$a->method_a(new $cn);
}
catch(Error $err) {
echo "catched: ", $err->getMessage(), PHP_EOL;
}
}
echo 'done.';
인쇄물
catched: Argument 1 passed to ClassA::method_a() must be an instance of ClassB, instance of ClassA given, called in [...]
catched: Argument 1 passed to ClassA::method_a() must be an instance of ClassB, instance of ClassWrong given, called in [...]
method_a: ClassB
method_a: ClassC
done.
PHP7 이전 버전에 대한 이전 답변:
http://docs.php.net/errorfunc.constants 말한다:
E_RECOVERABLE_ERROR(정수)
포착 가능한 치명적인 오류.이는 아마도 위험한 오류가 발생했지만 엔진을 불안정한 상태로 두지 않았음을 나타냅니다.사용자 정의 핸들로 오류를 포착하지 못한 경우(참조: set_error_handler()), E_ERROR로 인해 애플리케이션이 중단됩니다.
또한보십시오: http://derickrethans.nl/erecoverableerror.html
예를 들어
function myErrorHandler($errno, $errstr, $errfile, $errline) {
if ( E_RECOVERABLE_ERROR===$errno ) {
echo "'catched' catchable fatal error\n";
return true;
}
return false;
}
set_error_handler('myErrorHandler');
class ClassA {
public function method_a (ClassB $b) {}
}
class ClassWrong{}
$a = new ClassA;
$a->method_a(new ClassWrong);
echo 'done.';
인쇄물
'catched' catchable fatal error
done.
편집하다:하지만 try-catch 블록을 사용하여 처리할 수 있는 예외를 "만들" 수 있습니다.
function myErrorHandler($errno, $errstr, $errfile, $errline) {
if ( E_RECOVERABLE_ERROR===$errno ) {
echo "'catched' catchable fatal error\n";
throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
// return true;
}
return false;
}
set_error_handler('myErrorHandler');
class ClassA {
public function method_a (ClassB $b) {}
}
class ClassWrong{}
try{
$a = new ClassA;
$a->method_a(new ClassWrong);
}
catch(Exception $ex) {
echo "catched\n";
}
echo 'done.';
제휴하지 않습니다 StackOverflow