I appear to be in the minority here, but i prefer endforeach
, endif
etc over braces. They clearly specify which statement they're intended to close, unlike braces (which just close the closest still-open block).
<? if (someCondition): ?>
imagine a bunch of code here
<? foreach ($rows as $row): ?>
imagine a bunch more code here
<? endforeach ?> (without this, PHP complains about "unexpected T_ENDIF")
and a bunch more here
<? endif ?>
<? if (someCondition) { ?>
imagine a bunch of code here
<? foreach ($rows as $row) { ?>
imagine a bunch more code here
<? } ?> (without this, PHP complains about "unexpected $end")
and a bunch more here
<? } ?>
In the first example, the error is pretty much confined to the if
block (and whatever is inside of it), and PHP chokes on it sooner (and thus, closer to the real error). In the second, PHP gets all the way to the end of the script before realizing the braces don't match up. That's potentially a whole lot more code to look for a missing brace in.
The people preferring braces are all like "well, if you indent your code properly, braces are just as readable". The thing is, though, there are a couple of issues:
- Not everyone is as religious about code formatting as you. Particularly that new guy that's fixing your code while you're on vacation.
- Braces are not "just as readable". Period. I don't care how much you like C, C#, Java, or whatever other language taught you that braces were a good thing. The fact is, there are far better syntaxes for control structures -- and PHP actually includes one.
- Braces are punctuation. A single char of punctuation. Often surrounded by other punctuation, at that. They're easy to miss. It seems to me like the brain actually tries to filter out punctuation half the time.
- I don't know about your editor, but mine highlights keywords. They stand out, and are longer, and are thus easier to spot. It highlights braces as well, and even attempts to highlight the matching brace...but no matter how brightly you color your braces, they're not going to stand out as well as a whole highlighted word.
- Braces just say "close something". They don't say what to close. They simply can't convey that info on their own. They rely on you to always (ALWAYS!) indent "properly", and savagely beat any programmer that doesn't (or uses spaces instead of tabs, or tabs instead of spaces, or whatever your pet coding style is). That, or you end up adding comments like
// end if
. And if you ever find yourself adding comments like that...why in the hell would you avoid a keyword that does the exact same thing, but can actually be verified by the interpreter?