views:

129

answers:

4

Is this an okay practice or an acceptable way to use PHP's error suppressing?

if (isset($_REQUEST['id']) && $_REQUEST['id'] == 6) {
  echo 'hi';
}

if (@$_REQUEST['id'] == 6) {
  echo 'hi';
}

EDIT:
I thought so too. The code (and idea) is from friend.
Thanks for proving me right. :)

+2  A: 

i always use isset() as it's more specific. Also, i'd use a more specific superglobal variable, so use either $_POST, $_GET, $_SESSION. Being clear with your code avoids headaches later on :)

This is how i run my checks:

if(isset($_POST['id']) && $_POST['id'] == '6')
{
     // do stuff
}

This is pretty thorough checking, since it checks for an existance of a post, then whether my variable is part of the post, and finally if those two pass, it checks to see if my variable is equal to 6.

Rob
The initial boolean check for `$_POST` is unnecessary. Also, using `isset` is preferred to using `array_key_exists`, it's many times faster. The only advantage is if you want to check if 'id' exists but is null.
ryeguy
@ryeguy thanks for the advice! :) thinking about it now yeah its a bit silly since array_key_exists iterates over the array doesn't it?
Rob
@Rob I initially thought this too, but it isn't true. If you benchmark `array_key_exists` you'll realize it's `O(1)`, just like `isset`. I think `isset` is quicker simply because it's a language construct, so there is no function call overhead like there is to `array_key_exists`.
ryeguy
+11  A: 

It's not a really good practice to use error suppressing. It's even not a good practice to use $_REQUEST at all. Just use isset() or !empty() or whatever, don't be lazy.

And one more thing, it is a "good practice" to close parenthesis when using isset() :)

Kemo
You can also use `array_key_exists` to check if variable send by browser
Ivan Nevostruev
yeah, that's why I added "or whatever" :)
Kemo
I've upvoted this, but for completeness you could add some explanation for the OP about the reasons.
Gordon
+3  A: 

No, it's not really an acceptable practice in my opinion. Apart from the fact that it looks sloppy, custom error handlers are still triggered even when using error suppression.

The manual offers more reasons to avoid its use altogether:

Currently the "@" error-control operator prefix will even disable error reporting for critical errors that will terminate script execution. Among other things, this means that if you use "@" to suppress errors from a certain function and either it isn't available or has been mistyped, the script will die right there with no indication as to why.

nickf
+2  A: 

Suppressing the errors using @ only suppresses the display of the error, not the creation. So you get a small performance hit from the error if you don't check isset() first.

Scott Saunders