How (and Why) to Use Comments in PHP

Created by Danish-Canadian programmer Rasmus Lerdorf in 1994, PHP is a popular server-side scripting language that’s commonly used for web development. If you’re new the world of PHP, you may encounter messages embedded into the code. Known as “comments,” they allow programmers to leave notes without affecting the actual PHP script or function. To learn more about comments in PHP and how to use, keep reading.

Reasons to Use Comments in PHP

Generally speaking, there are two primary reasons to include comments in PHP.

  1. To remind yourself of what you did. As a PHP programmer, you’ll be sifting through and editing countless lines of code on a regular basis. Whether you’re writing a new script or editing an existing script, you should leave comments to remind yourself of what you did. If you need to debug or edit the script in the future, seeing these comments will provide transparency into the mechanics of the PHP code.
  2. To let others know what you did (or plan to do). When collaborating with other programmers, you can let them know what you did or plan to do by adding a comment. Other programmers will see your comments when they open the file, making this an invaluable tool in your PHP programming arsenal. If you recently changed the code to fix an error, you may want to leave a comment so the other programmer(s) know about the fix. Otherwise, they may go back and undo your changes.

How to the Leave Comments in PHP

Leaving comments in PHP is quick and painless. Just write your comment anywhere inside the PHP file and add the appropriate opening and closing tags. When done correctly, the comment will remain visible on the file but will not affect the execution of the PHP code.

You can see below for examples of how to leave comments in PHP, but it basically consists of either single line or multiple line comments. If your comment fits on a single line, you should use either the first or second example shown below. But if your comment contains multiple lines, you’ll need to use the format shown in the last example.

Single Line Comments in PHP: Example #1)

<?php
#This is a comment on a single line
?>

Single Line Comments in PHP: Example #2)

<?php 
//This is another comment on a single line 
?>

Multiple Lines Comment Block

<?php
 /* 
This is a multiple lines comment block
that you can include, well, on multiple lines
 */ 
 ?> 

 
Online Technology Courses Stone River eLearning

GET YOUR FREE PHP EBOOK!

Comments