How can I use the error control operator (@
) in constructors?
The constructor for \DateTime
will both throw an exception and raise a warning if a wrong argument is passed, but I would rather be able to catch
the exception and handle it, and not get the warning. For this reason I would like to silence the warning e.g. using @
.
If I catch the exception, the warning is still raised. I could try using the @
operator (although I don't know if it also prevents the exception from being raised). But I cannot get the syntax for this use case.
PHP version under test is 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