Monday, March 4, 2013

Difference between foo() and @foo() in php?

@foo() suppresses errors. If foo() triggers an error, warning or a notice, it won't get displayed/logged even if error_reporting is set to display/log them. (Note that errors still cause PHP to stop executing - it just won't display/log anything).

In general, you should NOT be using this kind of error suppression unless you're checking for errors another way - it's not a good idea to keep anyone from knowing about errors that come up. Furthermore, if your code is ALWAYS returning some kind of non-fatal error, you need to fix that, not hide it - also, what happens if an error you DIDN'T expect come up?

If foo() returns FALSE and raises a warning on failure (for example), you could do something like this: (bar() is called only if foo() fails and returns false)

 So simply using a @ sign before a function call will not output errors related to that function

foo() executes the function and any parse/syntax/thrown errors will be displayed on the page.

@foo() will mask any parse/syntax/thrown errors as it executes.
You will commonly find most applications use @mysql_connect() to hide mysql errors or @mysql_query. However, I feel that approach is significantly flawed as you should never hide errors, rather you should manage them accordingly and if you can, fix them.
<code>
@foo() or bar();
</code>

or

<code>
if ( @foo() === FALSE ) {
// foo() failed! do something here
}
</code>

No comments:

Post a Comment