PHP endswitch; - Is this normally practiced?
I was reading some switch statements and noticed 开发者_C百科one using endswitch;
. Why or why not should one use this? Is it even necessary?
It is used if you use the alternative syntax for control structures.
Thus you could either choose
switch ($var) {
case 1:
echo "Hello!\n";
break;
case 2:
echo "Goodbye!\n";
break;
default:
echo "I only understand 1 and 2.\n";
}
or
switch ($var):
case 1:
echo "Hello!\n";
break;
case 2:
echo "Goodbye!\n";
break;
default:
echo "I only understand 1 and 2.\n";
endswitch;
They are functionally identical, and merely provided as syntactic sugar.
+1 TO Amber. The alternative syntax is no doubt more readable, especially when inserting control structures among HTML. And yes, the accepted coding standards varies on the organization. In our case, we use the if(): endif in templates, and if(){} in logic and backend portion of the code. Observe the neatness of the code, including the indentation:
<?php if($number %2 != 0):?>
<p>I guess the number is odd</p>
<?php else:?>
<p>I guess the number is even</p>
<?php endif?>
In this case, you don't even need that pesky semicolon in the end.
Just to compare, here is the "unalternative" (or original) way:
<?php if($number %2 != 0) {?>
<p>I guess the number is odd</p>
<?php } else {?>
<p>I guess the number is even</p>
<?php }?>
Observe the aesthetically-disturbing curly braces all over the code. The first style fits better with HTML tags.
I've never used the switch variant, but for if statements or for statements it can be handy in templates.
But It's mostly a matter of taste.
The alternative syntax is very nice in template files.
The usual systax for switch statements in c-style languages is like this:
switch($foo) {
case 1: foobar();
break;
case 2: something();
break;
case 3: whatever();
break;
default: anything();
}
Never saw "endswitch" in actual production code.
I'd recommend sticking to the accepted coding standards to keep your code readable and maintainable.
精彩评论