Articles in Basics Category

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.

After some time, having no standard can make it difficult to understand even your own code.

Over the past, Zend Framework Coding Standards and Pear Coding Standards were widely followed. However now more attention has been gained by PSR (PHP Specification Request) guides defined by PHP Framework Interop Group. You may want to check their Basic Coding Standard (PSR-1) and Coding Style Guide (PSR-2).

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 simple programs because if you get 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, lowercase is used and uppercase 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 uppercase.
  • Numbers can be used but discouraged.
$en = 'Robin Jackman'; // Not acceptable. $en is not descriptive
$employee_name = 'Robin Jackman'; // Not acceptable. Underscore is used.
$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 even for 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';
Where to Head from Here...
Share with Your Peers...

We Value Your Feedback...

We love to hear what you think about this article. Please provide your opinion, suggestions and improvements using following form. Note that submitted feedback is not displayed but we will get back to you if it needs a reply.