Monday, May 14th, 2007
Format your PHP Code
After fixing my wireless issues with Kubuntu Feisty, I went on a little break. I was sick of looking at my dual monitors and eye-candy rotating desktop cube *rotates cube* - well ok… maybe not the cube, but now that I’m back, I’d like to bring your attention to formatting your PHP code.
Properly formatting code is one of the first steps I took to writing quality code. Formatting your code is something that is usually not mentioned so much in beginner’s circles as users usually pick up from examples.
“Formatting” is a very general term, so let me just clarify the context I’m using it in. My meaning when using the term “Formatting” is the way you lay out your code blocks. This applies to conditional statements (such as if else elseif) and loops (for, while) and constructs like functions, classes and even comments.
Here are some examples:
With conditionals and loops, I like to keep the opening brace on the same line as the construct keyword and indent the code executed within the loop 1 tab inward.
If statement
if ($someValue === false) {
$someResult = ”some value‘ variable is false’;
} elseif ($someValue === true) {
$someResult = ”some value‘ variable is true’;
} else {
$someResult = ”some value‘ variable neither boolean true or false’;
}
echo $someResult;
For Loops
For functions, classes and methods I enter the opening brace on the line below the construct keyword.
Function
{
//function logic
}
Classes
{
// method
public function getExample()
{
//method logic
}
}
Browsing through some applications, I find lots of horrendously unformatted code. Unformatted code not only makes it hard to follow previously written code, but makes applications especially hard to maintain causing headaches for people who are going to be maintaining code you have released and to you also when the time comes to revisit the code you have previously written a few weeks down the line.
So to conclude. Format your code, come up with a formatting scheme and stick to it. It’s a good practice which solves readability issues, which in turn aids in maintenance and ultimately puts you on the right track to quality code.