【发布时间】:2018-01-10 13:57:17
【问题描述】:
如何在构造函数中使用错误控制运算符 (@)?
如果传递了错误的参数,\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
【问题讨论】:
标签: php error-handling constructor syntax-error php-7