Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I've being using this trick for years instead of the ugly

    isset($array['key']) ? $array['key'] : null;
thinking I was simply ignoring those stupid "Undefined index" notices.

Now I figure out I was also hiding "Undefined variable" notices when $array was not defined and a ton of potential errors when $array is an object implementing ArrayAccess.

Shame on me.



Finally, an explanation for why it's a bad idea, after all these people just going "it's a misuse", "impressively awful", "really horrible"...

Thanks.

Note to self: grep the code at work for @. Purge.


Yes, the main issue with using @ is that it conceals side effects and sweeps all errors under the rug -- including the ones that you may actually want to handle.

Although there may be some scenarios where it's permissible, such as @unlinking temporary files when upload validation fails. It only happens in exceptional cases, the outcome is not immediately crucial, and you don't have any dependent operations.

All of this is moot when you do the following though:

- Set error_reporting to -1 (report ALL errors)

- Register a custom error handler that converts all errors to exceptions

This renders the @ operator useless (it'll throw an exception regardless). I personally prefer this since it enforces error handling discipline early on.


That's an interesting idea on the custom error handler, I wasn't aware that those trigger regardless of @s.

I guess a lot of the trouble with @ is that it affects everything that happens temporally-within the expression, but people often use it as if it only affects everything syntactically-within it... for instance, recently I came across something like:

    // suppress warning for <2 results
    @list ($foo, $bar) = returns_a_list(...);
... which would also hide any warnings that occur in the body of returns_a_list(), despite that being neither intended nor wanted.

It's a shame the only @-free solutions to many popular uses of @ (like that one) are so hideously ugly. Also that I suspect that changing @ so it only affected syntactically-contained errors would be... impractical for the PHP team, for a number of reasons.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: