Commenting Out in PHP

Comments can be a PHP programmer’s best friend. Even if you are writing the code for yourself, chances are there will come a day when you’ll forget what some of your code actually does. A few simple comments written throughout the code can be extremely helpful in this regard. Because simple comments won’t always cut it, more detailed comments can also be used to explain your more complicated pieces of code.

Though comments can be used under any circumstances, it becomes especially important to include them if other people will be working on your PHP files in the future. Making sure to write comments throughout the file will help other programmers to better understand your code when making any changes of their own.

Don’t worry about adding too many comments in your PHP code. It is always better to have too many comments than too few. Also, unlike HTML comments, there is no need to worry about your comments showing up in the source code of a web page. The only place where PHP coded comments are visible is in the actual PHP file itself.

Now, there are a few ways that you can add comments to your PHP files. If you are making just a short comment, you can precede it with either a “#” or “//”. Either of these options will comment out anything following the # or // symbols, as long as they appear on the same line.

Example:

<?PHP

# This is a comment.

// This is also a comment.

?>

Neither of the PHP comments in the previous example would appear in a browser’s source code of the web page. This is because as mentioned above, any PHP comments used within the code will only appear in the actual PHP file.
For times when you’d like to make a comment about a more complicated piece of your code, you may wish to use the ” /* ” and ” */ ” symbols instead. This type of code is used for multi-line comments and will comment out anything that falls between the initial /* and the following */.

Example:

<?PHP

/* This is a multi-line comment written in PHP.

Multi-line comments are used to describe more complicated pieces of code and often contain specific details about the code itself, what the code can be used for, or who created the original piece of code. */

?>

Just like in the first example, the PHP snippet shown above would not appear when viewing the source code in a web browser. Multi-line comments are only visible in the PHP file itself, regardless of their size or the number of line breaks used between the opening /* and the closing */.

The more experienced you become at coding PHP, the more complicated your code is bound to become. Be sure to add plenty of comments so that your future self and others will be able to easily understand exactly what you have coded. Adding ample PHP comments can save yourself and others a great deal of frustration in the future.