Control Structures
In this lesson we will look at the styling rules for control structures.
The general style rules for control structures are as follows:
-
There MUST be one space after the control structure keyword
-
There MUST NOT be a space after the opening parenthesis
-
There MUST NOT be a space before the closing parenthesis
-
There MUST be one space between the closing parenthesis and the opening brace
-
The structure body MUST be indented once
-
The closing brace MUST be on the next line after the body
The body of each structure MUST be enclosed by braces. This standardizes how the structures look, and reduces the likelihood of introducing errors as new lines get added to the body.
if, elseif, else
An if
structure looks like the following.
Note the placement of parentheses, spaces, and braces; and that
else
andelseif
are on the same line as the closing brace from the earlier body.
<?phpif ($expr1) {// if body} elseif ($expr2) {// elseif body} else {// else body;}
The keyword elseif
SHOULD be used instead of else if
so that all control keywords look like single words.
switch, case
A switch
structure looks like the following.
Note the placement of parentheses, spaces, and braces.
The case statement MUST be indented once from switch
, and the break
keyword (or other terminating keyword) MUST be indented at the same level as the case
body.
There MUST be a comment such as // no break
when fall-through is intentional in a non-empty case
body.
<?phpswitch ($expr) {case 0:echo 'First case, with a break';break;case 1:echo 'Second case, which falls through';// no breakcase 2:case 3:case 4:echo 'Third case, return instead of break';return;default:echo 'Default case';break;}
while, do while
A while
statement looks like the following.
Note the placement of parentheses, spaces, and braces.
<?phpwhile ($expr) {// structure body}
Similarly, a do while
statement looks like the following.
Note the placement of parentheses, spaces, and braces.
<?phpdo {// structure body;} while ($expr);
for
A for
statement looks like the following. Note the placement of parentheses, spaces, and braces.
<?phpfor ($i = 0; $i < 10; $i++) {// for body}
foreach
A foreach
statement looks like the following.
Note the placement of parentheses, spaces, and braces.
<?phpforeach ($iterable as $key => $value) {// foreach body}
try, catch
A try catch
block looks like the following. Note the placement of parentheses, spaces, and braces.
<?phptry {// try body} catch (FirstExceptionType $e) {// catch body} catch (OtherExceptionType $e) {// catch body}