PHP Error Control Operator
PHP Error Control
@)PHP also supports an error control operator - at the sign, this sign is prepended before an expression and will be suppressed/ignored if any diagnostic error is generated in that expression.
For Example -
<?php $x = $arr[0]; // Error : PHP Warning: Trying to access array offset on value of type null. ?>
In the above example, if an array variable is not defined and still tried to access it, an error like this occurred. To avoid this you @can simply prepend.
As
<?php
$x = @$arr[0];
?>
Get Error Message
Now the error is controlled, but now if you want to know the error message then you error_get_last()can call the function which returns an Associative Array about the last error.
<?php
$x = @$arr[0];
print_r(error_get_last());
?>
Output
Array
(
[type] => 2
[message] => Trying to access array offset on value of type null
[file] => C:\Users\verma\Desktop\test.php
[line] => 2
)
Now you can easily access the message key from this array and print the error message.
Important
Internally the operator sets @the error reporting level for that particular line so that only warning and parse errors are ignored. However Fatal Errors cannot be prevented by this.0
Like in the example given below the undefined function test()was called.
<?php $x = @test(); // Fatal error: Uncaught Error: Call to undefined function test() ?>
Use the Error Control Operator @ as little as possible, it slows down the execution and performance, although you can set a default value to the variables as per the need.