Coding Standards
Sticking to coding standards help you to keep consistency and make your code understandable to others. It’s really helpful when you work on big projects where more than one programmer may work on and that you have to deal with great amount of code (Having no standard can make it difficult to understand your own code after some time).
There are few well defined coding standards. Zend Framework Coding Standards and Pear Coding Standards are two of them that you can learn a lot. When you develop, you may make slight changes to the standard you chose to suite your needs. As long as your changes are consistent and acceptable within the project you are working on, it should be ok.
In some places you would see Coding Standards are referred as Coding Conventions merely because they are conventions rather than rules (Your program may not stop working if you break them but your code may not be accepted in a place where coding standards are given considerable attention).
Following conventions are few that you worth follow even in your own simple programs because if you used to break them it would be bit difficult to adhere to them later.
Use CamelCase in Naming
CamelCase is highly used in Object Oriented Programming and below are few aspects of it.
- Avoid using abbreviations and use descriptive words.
- For variable names and function (methods in OOP terminology) names, lower case is used and upper case is used for the first letter of next word when more than one word is used.
- Same conventions are used for class names. Additionally, first letter of the first word also should be upper case.
- Numbers can be used but discouraged.
$en = 'Robin Jackman'; // Not acceptable. $en is not descriptive $employee_name = 'Robin Jackman'; // Not acceptable. Underscore is not allowed. $employeeName = 'Robin Jackman'; // Acceptable.
Use Braces Consistently
In some cases, PHP allows to omit braces for code blocks. For an example, following would work just fine.
$value = 6; if ($value < 10) echo 'Value is accepted';
But it’s highly encouraged to use braces for even simple cases like this because otherwise it makes harder to read code and understand which statement belongs to which part. So, above code block should be corrected as below.
$value = 6;
if ($value < 10) {
echo 'Value is accepted';
}
In some coding standards (for an example in Zend), it’s instructed to have opening brace in the same line of the condition for control structures (as illustrated above). However when it comes to function declaration, it’s instructed to have the opening brace in a new line. So, following is the accepted function declaration.
function getEmployeeName()
{
// Function body goes here
}
However having the opening brace in the same line as in control structures is also in use. And PHPKnowHow follows that way, so you would see function declaration as below.
function getEmployeeName() {
// Function body goes here
}
