PHP encoding methods

If I get a variable and I don’t know if it is set or not, I can write

if (isset($a) && $a > 2) 

or i can write

 if (@ $a > 2) 

which is shorter. Is the second syntax good or not?

+7
php
source share
5 answers

I totally sympathize , but suppressing the error with @ is bad practice.

The error is still happening, it just blocks. This requires microscopic amounts of time that can accumulate if they are performed in cycles.

In addition, you remove the possibility of using the "undefined variable" notifications to your advantage: as a mechanism to avoid typos.

+10
source share

The if(@$a) expression does not check if a variable is set or not. The @ character simply suppresses any warnings that constitute a bad coding style.

+15
source share

The first approach is the right approach. The second approach is very bad. you will end up with suppressed errors, and you won't even know. and one day you will have errors that you cannot debug from this bad practice,

+3
source share

The isset function checks if a variable exists, and if it is not equal to zero. I'm not quite sure what you want to achieve with && $ A.

The @ operator suppresses error messages generated by the expression to which it was added.

+2
source share

As people have said, the first option is the path. Actually, I don't like the option (/ * * / & & $ var) to check if a variable is empty. I prefer to use

 if (isset($var) && !empty($var)) { /* foo */ } 

or simply

 if (!empty($var)) { /* foo */ } 
+2
source share

All Articles