If I get a variable and I don't know is it set or not I can write
if (isset($a) && $a > 2)
开发者_Go百科or I can write
if (@ $a > 2)
which is shorter. Is the second syntax good or not?
The expression if(@$a)
does not check whether the variable is set or not. The @ symbol just surpresses any warnings which is a bad coding style.
I totally sympathize, but suppressing the error using @
is bad practice.
The error still occurs, it just gets suppressed. It costs microscopical amounts of time that can however accumulate to a lot if done in loops.
Also, you take away the possibility to use "undefined variable" notices to your advantage: As a mechanism to avoid typos.
The first approach is the right approach. The second approach is very bad,. you will end up with errors being suppressed and you wouldn't even know,. and one day you will have errors cropping up that you wouldn't be able to debug its that bad a practice,.
The function isset checks if a variable exists and if it is not null. I'm not quite sure what you want to achieve with the && $a.
The @ operator suppresses the error messages generated by the expression it was prepended to.
Like people already told, the first variant is the way to go. Actually I dislike the (/* */ && $var) variant to check if the variable is empty. I prefer using
if (isset($var) && !empty($var)) {
/* foo */
}
or just
if (!empty($var)) {
/* foo */
}
精彩评论