Google+ Followers

donderdag 12 november 2015

Why will OR DIE() not just... well, die?

"or die()" is possibly the stupidest thing in PHP. Every experienced PHP programmer will tell you that it's a bad idea and that PHP supports exceptions. Pretty much every other language has a structure for stopping a script with some sort of ternary OR operator, but you rarely see it used.

The problem with "or die()" is of course that 'die()' literally stops the script, right there and then. But in just about every case I've ever seen, the programmer did not want that, he wanted to stop further processing.

What's the difference? When you "stop further processing", you simply skip that part of the script that you cannot execute because of the error. All the code that is not affected by the error is still executed. This is important because "the rest of the code" includes the code that reports the error that was encoutered. If you just stop the script then no output is generated and your visitor will see a blank page that does not even tell him that there was an error. He cant report the error to you, he can't continue to a different page, he will press F5 to see if the page just failed to load, and when it doesn't he will go to a different website.

Not stopping the script also prevents you from corrupting your data. For example; if your script opens a file to write new content to it, you will typically (not correctly, but typically) open the file, reset it and then start processing and writing new content. If the orocessing fails and you stop the script outright, you will be left with an incomplete file, which breaks other processes. Brilliant.

When you stop further processing, you abort the processing and writing of the new content, and you will logically come to a point where you wonder ök, so what do I do with the fileif I can't update it?" and then you take the proper route where you write the new content to a new file and do a delete/rename once you have confirmed that the new file is correct.

There is no need for or-die() and it really doesn't matter if you think that it's easy to sue during debugging, because you *will* forget a couple of these statements and the *will* break your data.

Yeah, it's won't hapen to you, of course not, untill it does.

Use exceptions. Start your script with proper error handling, it will save your bacon.