Adding a Comment to a PHP Code Page

June 4, 2009 by: Allen Sanford

Comments are actually the most important thing any coder can learn to properly use. There are actually a few different styles to use when commenting code for PHP. In this tutorial I am mostly going to let the code do the speaking … so to speak …?! Any way. Let me get a few important things out of they way first. The PHP interpreter ignores comments so you can only gain an advantage by adding then. Six months or a year down the road their usefulness out weights the trouble of adding them to your code. And lastly you can put your contact information in the comments of your code so when you pass you code out as open source somebody will notice that you wrote it. OH yeah I forgot to mention you can use them to debug code as well.

First style that you will see is in line or single line comments and they can be used two ways.

?Download example.php
42
43
44
45
46
 
    foreach ($rows as $row) // This loops through every row of rows
    {
        // TODO: Implement something cool here
    }

Second style is to use multi-line comments, this is used by the famous phpDocumentor project.

?Download example.php
42
43
44
45
46
47
48
49
50
51
52
53
 
    /*
        I know that I want to implement this loop later
        but I don't want to run a loop that does nothing
        either so for know I am going to comment out
        all of this.
        Cool!
        foreach ($rows as $row)
        {
            // TODO: Implement something cool here
        }
    */

Third style is the less familiar but oh so useful if stament comment. Allowing you to wrap large blocks of code with an if statement to comment it out.

?Download example.php
42
43
44
45
46
47
48
49
 
    if (0) // This will skip this block of code thereby not executing a loop that does nothing
    {
        foreach ($rows as $row)
        {
            // TODO: Implement something cool here
        }
    } // End if (0)

Filed under: PHP
Tags: , , ,

Leave a Reply