简体   繁体   中英

Is using “@” to suppress warnings/notices right?

I guess, the title itself explains the question....:)

Is it right to use @ to suppress PHP warnings and notices? For example, In:-

if (isset($someArray['somekey'])) {
    $myVar = $someArray['somekey'];
}

and in:-

$myVar = @$someArray['somekey'];

which one is right way? And why the other one is wrong?

Is it right to use @ to suppress PHP warnings and notices ?

No

which one is right way?

The first method.

And why the other one is wrong?

Both the methods makes $myVar to be assigned a NULL , but you should not try to suppress errors/warnings.


Explanation for your comment :

Well you don't wanna know what caused your script to show some weird output when you are expecting something else?

Say if you are running this code.. echo $source=file_get_contents("http://www.google.com"); Consider if google.com is down then you would get an notice on your script like ..'hostname not found` , By reading this informational message , you could very well know that your code is right but the issue is only with Google Servers.

Say if you had echo $source=@file_get_contents("http://www.google.com"); , Nothing would be printed , However you would be expecting a HTML source.

Are you getting the picture ?

you shouldn't write code which produces warnings, however, you should turn off warnings and notices when running in production environment. and that is done through a global settings through error_reporting

No, you should not suppress errors with @ . When you're developing you'll want to be able to see errors, and in production your project should have error reporting turned off via php.ini rather than @ .

turn of warning and notice errors by putting

error_reporting(E_ALL ^ (E_NOTICE | E_WARNING))

in top of your code in production level and handle errors with a custom error reporting method written by yourself.

but in development level just put error_reporting(E_ALL ^ E_NOTICE) and read the errors, notices are not important, even in development level.

one of the advantages of preventing warning errors with error_reporting , is that even in the production level , if a problem occurs, you can simply debug it by changing the error_reporting value to E_ALL and read the errors and solve it .

here is the manual of errro_reporting() function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM