The importance of PHP Coding Standards... (how I roll)

I remember very well how appalling my first few lines of PHP were. I was just getting stuck into learning PHP and I felt like I already knew all there was to know, how wrong I was.

When I first began coding I didn't give a second thought to what my code looked like, as long as when I ran it, it worked (kinda) I was happy. In the beginning everything was simple. I generally worked alone and the tasks that I worked on were fairly basic. The problems came when I began coding my first major project, with 4/5 other coders and they had to be able to read my code and vice versa.

I soon realised that though I could write PHP that was functional it was a mess to look at, no consistency existed and sometimes even I couldn't understand what was going on. This problem was magnified when the 4 or 5 coders came together to merge their beautiful PHP creations into one big monster.

We got in a mess, try making heads or tails of this nonsense. By the way this wasn't any code we wrote, just an example of how badly it was written.

    $AVariable = 1;
if ($errorMSG) { echo "This PHP Stuff is amazing";} else { echo $errorMSG; }

As you can see this is a jumbled mess. Indentation all over the place, inconsistent variable casing and inconsistent control structure construction. I'm going to give you pointers now on how to avoid this jumbled up confusing coding style and achieve PHP code that is much more readable and less likely to be full of errors.

$aVariable = 1;

if ($aVariable) {
    $errorMsg = false;
    if ($errorMsg) { 
        echo "This PHP Stuff is amazing";
    } else { 
        echo $errorMsg; 

Just agreeing on variable casing and indentation will make your code much easier to read. As you can see above it is already a huge improvement over the original.

When starting any project with more than one developer I suggest getting together and agreeing on some coding standards. This will make it easier for you all to read each others PHP code and understand it. I live by the mantra that code should be written so that anyone else who comes along can make sense of it.

I generally work off the Zend Framework Coding Standards the reason for this is because I use Zend Framework everyday at work and I find it the most comfortable. There are loads of sets of coding standards out there check out wikipedia and this quick google search I did PHP Coding Standards.

You will notice that many PHP frameworks have their own standards have a look through them and pick the one you are most comfortable with and stick to it. If you don't like any of them then go ahead, develop your own.

Adopting coding standards will be one of the best things you'll ever do in your development career.

No comments:

Post a Comment