0

I was wondering what the use cases are to use the @ symbol in PHP to suppress errors for an expression.

It is discouraged by a lot of people for good reasons but I was wondering when it actually can help to write cleaner code. I came across the following example where the validation of the object is done inside and outside the function. Validation done inside the function can sometimes mean you can keep your code outside of the function cleaner.

Validation outside the function:

if (isset($object)) {
    a($object);
}

function a($object) {
}

Validation inside the function with use of @:

a(@$object);

function a($object) {
    if (!isset($object)) {
        return false;
    }
}

Are there any good use cases for the @ symbol?

I know what the @ symbol does, but not when to use it

Daan
  • 7,685
  • 5
  • 43
  • 52

2 Answers2

2

@ is one of the things that gives PHP reputation of a bad language - it allows you to write bad code.

I personally was using @ for unlink() - this is the case I can probably still accept sometimes if doing code review, but will not do it myself.

1

You can use this when you're working with code (or application) that can not be changed by you (like external API or encoded modules) and it can crash your script (for example generate fatal error).

But first of all you MUST handle such situations - generate your own exception and create acceptable catching for it (without script crashing and PHP warnings on page but with suitable message for user or admin).

Because otherwise debug becomes very hard.

Slava
  • 878
  • 5
  • 8