PHP @ instead of isset to check the value of $ _GET

Give me one good reason to do it.

if( isset($_GET['key']) && ($_GET['key'] === '123') ) {... 

instead of this

 if( @$_GET['key'] === '123' ) {... 

I ask about this particular case of code , not at all!

The following reasons are not welcome:

  • β€œUsing @ slow the application down for a few nanoseconds, because the error is still generated (even if it is suppressed).” I prefer slower code, but more readable.
  • "using @ is a bad habit." This may be true in general, but I do not believe in this case (besides, bad habits may depend on the context, they suggest using @ in PHP functions like fopen in @ in certain circumstances, see Errors / Exceptions at http: // www.php.net/manual/en/function.fopen.php )
+4
source share
3 answers

The performance impact is not really the best argument against this example, and you will need to measure the performance of your own application to decide if this is a problem. Most likely, this will lead to a slowdown if a large number of elements to be checked are not installed or if you set such a check in a loop.

The main problem with using the @ operator is that it can become a convention in your code, so while your example may seem harmless, you can later find yourself or your team using:

 if( @IsAvailable() ) { 

And suppression of errors begins to hide real errors that you did not expect, as well as those that you did - and you do not know what happened when you do not receive any information about the exception.

+4
source

Think about how much you can slow down your application when your site / application begins to receive tens / hundreds of thousands (or more) requests per day. If you suppress errors as a standard, you probably have dozens for each request - all of a sudden, you're on the site noticeably slower than you would like.

In addition to this, you can end up suppressing errors that you really want to know about when developing.

+1
source

If you do not accept the performance issue as an argument, then this is really normal. But this should not be in all cases, because @ will suppress all possible errors, even those that you did not think about. But in this case, it seems there are no other possible errors that you want to suppress.

I agree with you that preceed isset () before reading the value is very ugly, and I also do not want to write it. But inserting @ before the expression seems ugly. This can reduce readability in longer code.

The good news is that with PHP 7 can we use a much better way, a null- bound operator ?? which works as follows:

 if($_GET['key'] ?? '' === '123' ) {} 

This is basically a replacement:

 $result = isset($value) ? $value : $anotherValue; 

now you can use

 $result = $value ?? $anotherValue; 
0
source

All Articles