PHP commenting standards

Taken from http://www.kevinwilliampang.com/2008/08/28/top-10-things-that-annoy-programmers/

Comments that explain the “how” but not the “why”

Introductory-level programming courses teach students to comment early and comment often. The idea is that it’s better to have too many comments than to have too few. Unfortunately, many programmers seem to take this as a personal challenge to comment every single line of code. This is why you will often see something like this code snippit taken from Jeff Atwood’s post on Coding Without Comments:

r = n / 2; // Set r to n divided by 2
// Loop while r - (n/r) is greater than t
while ( abs( r - (n/r) ) > t ) {
    r = 0.5 * ( r + (n/r) ); // Set r to half of r + (n/r)
}

Do you have any idea what this code does? Me neither. The problem is that while there are plenty of comments describing what the code is doing, there are none describing why it’s doing it.

Now, consider the same code with a different commenting methodology:

// square root of n with Newton-Raphson approximation
r = n / 2;
while ( abs( r - (n/r) ) > t ) {
    r = 0.5 * ( r + (n/r) );
}

Much better! We still might not understand exactly what’s going on here, but at least we have a starting point.

Comments are supposed to help the reader understand the code, not the syntax. It’s a fair assumption that the reader has a basic understanding of how a for loop works; there’s no need to add comments such as “// iterate over a list of customers”. What the reader is not going to be familiar with is why your code works and why you chose to write it the way you did.

also... phpdoc


In general, PHP seems to have a lot of different style guides...

  1. phpDocumentor style
  2. Zend Framework style
  3. Pear style

But in general, something to remember about commenting is... you probably don't want to comment every line in your code. Instead, try to make your code readable1 (as is.) And comment (mostly,) when you really need someone else to understand what your code is doing.

1http://www.codinghorror.com/blog/2008/07/coding-without-comments.html