Monday, February 05, 2007

A strange PHPism from the O'Reilly book

I've been working on a project where the front end is written in PHP and decided that I really needed to sit down and learn something about the language instead of just hacking my way through the existing scripts. I got a copy of Programming PHP and have been working my way page-by-page through the language.

On Page 54 I came across an example that I just can't figure out. I quote:

The do/while statement is sometimes used to break out of a block of code when an error condition occurs. For example:

do {
// do some stuff
if ($error_condition)
break;
// do some other stuff
} while (false);

Because the condition for the loop is false, the loop is executed only once, regardless of what happens inside the loop. However, if an error occurs, the code after the break is not evaluated.

Now, can someone in PHP land explain to my why you would do that when the following is much clearer and simpler:

// do some stuff
if (!$error_condition) {
// do some other stuff
}

And while I'm ranting WTF is the deal with variables essentially having no scope (a variable defined in inside a block is global: either global to the script or 'global' to the function definition the block is within).

2 comments:

Bart said...

The example is over-simplified. In most languages this technique would only be useful when you have a situation like

do {
// do some stuff
if ($error_condtion) {
// do something
break
} elseif ($other_condition) {
// do other thing
// do not break
} elseif ($third_condtion) {
// still no break
}
// do more stuff
} while (false);
// do final stuff

Remember, though, that PHP was designed first to be embedded in HTML documents where "stuff" and "thing" above might be chunks of raw HTML, and the structured code is broken up with < ? xpp and ? >, so it sometimes reads more cleanly and is more maintainable if you avoid having large chunks of code in a block protected by a test (it may be very hard to see the end of the block).

As for scoping ... same thing. Usually you want the variables to be visible in the HTML, which may be in a very different logical block than the PHP code that defined them. Although it has C-like syntax, PHP is a scripting language more like /bin/sh than like (say) perl or python.

Christian G. Warden said...

Maybe they were thinking of something like this:

do {
// do something
if ($error) break;
// do something else
if ($error) break;
// etc
} while (false);