-1

In PHP is possible to suppress errors by using the @ symbol before the statement.

Example:

if (@$flag[$i]) {
    ...
}

Although I have seen it used in many places, I have never seen a situation that was really necessary. As the error suppression was not yet removed from PHP (not even deprecated), I can assume it's really useful. Can someone point me a situation that it is really necessary?

darke
  • 31
  • 1
  • 4
  • 2
    Basically it's useful any time you explicitly, really, truly don't care if an operation produces an error. Though Stack Overflow is full of questions where developers used the error-suppression operator and then asked why their code isn't working. So it's definitely worth asking yourself if you explicitly, really, truly don't care if an operation produces an error. – David Oct 29 '20 at 19:34
  • The only time I've seen it *potentially* useful is to bypass the need for an `isset` check on an optional variable with strict warnings enabled. – ceejayoz Oct 29 '20 at 19:39

1 Answers1

1

It may be useful in cases when you need to call functions that can emit errors but you want to validate the reasons by yourself and take actions according to your own validations, avoiding errors leaking from your code. This situation is common when writing libraries, for example.

tonyfarney
  • 300
  • 3
  • 14
  • In most cases, a try/catch is a better approach to that. – ceejayoz Oct 29 '20 at 19:40
  • 1
    try { fopen(...); } will not suppress warnings to being emited – tonyfarney Oct 29 '20 at 19:43
  • It will if you set things up right. https://stackoverflow.com/questions/2071024/treating-warnings-as-errors (Laravel does this by default, incidentally.) – ceejayoz Oct 29 '20 at 20:12
  • @ceejayoz setting an error handler can be quite invasive for a library. A library should not overwrite any handler previously defined. It can set it's own handler at runtime, when it's methods are called but it's necessary to restore the previous one before the execution get back to the caller. Otherwise, the library could cause unexpected behavior for whom is using it. For a framework it's OK (and expected) to define an error handler, since is the framework who calls your code, not the opposite. – tonyfarney Oct 29 '20 at 23:34