如何在构造函数中使用错误控制运算符(@
)?
\DateTime
的构造函数将抛出异常并在传递错误参数时发出警告,但我宁愿能够catch
异常并处理它,并且不会收到警告。出于这个原因,我想沉默警告,例如使用@
。
如果我发现异常,则仍会发出警告。我可以尝试使用@
运算符(虽然我不知道它是否也可以阻止异常被引发)。但我无法获得此用例的语法。
正在测试的PHP版本是7.0.22。
❯ php -a
Interactive shell
php > new DateTime("abc");
PHP Warning: Uncaught Exception: DateTime::__construct(): Failed to parse time string (abc) at position 0 (a): The timezone could not be found in the database in php shell code:1
Stack trace:
#0 php shell code(1): DateTime->__construct('abc')
#1 {main}
thrown in php shell code on line 1
Warning: Uncaught Exception: DateTime::__construct(): Failed to parse time string (abc) at position 0 (a): The timezone could not be found in the database in php shell code:1
Stack trace:
#0 php shell code(1): DateTime->__construct('abc')
#1 {main}
thrown in php shell code on line 1
php > $a = @new DateTime("abc");
PHP Warning: Uncaught Exception: DateTime::__construct(): Failed to parse time string (abc) at position 0 (a): The timezone could not be found in the database in php shell code:1
Stack trace:
#0 php shell code(1): DateTime->__construct('abc')
#1 {main}
thrown in php shell code on line 1
Warning: Uncaught Exception: DateTime::__construct(): Failed to parse time string (abc) at position 0 (a): The timezone could not be found in the database in php shell code:1
Stack trace:
#0 php shell code(1): DateTime->__construct('abc')
#1 {main}
thrown in php shell code on line 1
php > $a = @(new DateTime("abc"));
PHP Warning: Uncaught Exception: DateTime::__construct(): Failed to parse time string (abc) at position 0 (a): The timezone could not be found in the database in php shell code:1
Stack trace:
#0 php shell code(1): DateTime->__construct('abc')
#1 {main}
thrown in php shell code on line 1
Warning: Uncaught Exception: DateTime::__construct(): Failed to parse time string (abc) at position 0 (a): The timezone could not be found in the database in php shell code:1
Stack trace:
#0 php shell code(1): DateTime->__construct('abc')
#1 {main}
thrown in php shell code on line 1
php >
php > $a = new @DateTime("abc");
PHP Parse error: syntax error, unexpected '@' in php shell code on line 1
Parse error: syntax error, unexpected '@' in php shell code on line 1
答案 0 :(得分:2)
为什么不使用try catch?
try {
$dt = new DateTime("abc");
} catch(Exception $e) {
// do wathever you want
}
答案 1 :(得分:1)
你可以做的是使用set_error_handler
的自定义处理函数,这样你就可以捕获"你想要的警告/错误。
这是一个我用来测试正则表达式是否有效的例子,我只是使用一个空函数,因为我不需要对警告做任何事情:
function filterRegularExpression($str) {
set_error_handler(function() {}, E_WARNING);
$isRegularExpression = preg_match($str, '') !== false;
restore_error_handler();
if($isRegularExpression){
return $str;
}
return false;
}
答案 2 :(得分:1)
您误解了产生警告的内容。警告由全局错误处理程序生成,因为您没有捕获异常并且它冒泡到顶部以终止程序(或者,在交互式CLI上生成警告)。线索是警告的前缀是“Uncaught Exception
”。如果捕获异常,则不会产生警告。 DateTime
构造函数不会产生自己的警告。