Aug 28 2010

It annoys me when I see tutorials for learning PHP with code like this:

$fd = @file("doesnotexist");

and this:

$md = mysql_connect("localhost", "user", "pass") or die("Could not connect!");

It’s bad practice in the real programming world and shouldn’t happen. The at symbol (@) is used to silence any errors caused by calling a function as shown above, when proper error handling should be implemented. Similarly, the practice of using “or die” to error check needs to stop being taught.

Using this language in PHP really needs to stop because there are much better ways to handle errors, such as using exceptions, or any sort of error handling except this really. My personal favourite is using an exception and catching it further down the stack. There’s loads of tutorials on error handling so I won’t go into it, but I just wanted to vent my hatred for this poor excuse for shoddy coding.

And while I’m at it, stop using mysql_* functions and start using PDO! :)

5 Responses to “Stop Using the PHP Error Suppressor “@” and “or die””

  1. Jasper says:

    The first example is about the only time it’s acceptable to use it, in my opinion. However, it would be nice if the built-in PHP file stuff threw exceptions so you could handle errors properly.

  2. James says:

    You could just write an error handler that throws exceptions perhaps? I’m sure I’ve seen that sort of thing before, although I’ve not done anything like it before.

    And I don’t 100% agree – you can use fexists, is_readable and is_writeable etc. to verify that the file exists, and that you have permissions to read from/write to the file and so on. Admittedly it takes much longer to write all that sort of verification, but if you use a framework often to write code, why not submit (or if it’s homegrown, just write) a patch to simplify the process?

  3. Jasper says:

    The only time I ever really use the error suppressor is when getting remote files that I probably don’t have access to. Granted, it’d be much better to write a custom stream modifier to cater for timeouts and 404s, but who has time for all that! :p

  4. James says:

    Quite – writing proper code like that can be very time consuming and I think any decent programmer can look at another’s code and say “why didn’t you do that, that’s a flaw in your code” and you can turn around and say “I was on a deadline”… It crops up numerous times, which I think is why I still enjoy writing code in my own time, with no restrictions on time – that’s probably when I write my best code to be honest!

  5. Benjie Gillam says:

    Hear, hear!

Leave a Reply