PHP Comments

Comments on source code will be useful for denoting the details the code logic. For an example, if we define a function in our program, we should add comment lines to state about the parameters passed to the function, what the function is doing and what it returns. These comment lines will be useful to understand the code easily. Adding comments on source code is the best programming practice.

As like as many programming languages PHP also supports two types of commenting styles, those are the single-line comment and the multi-line comment.

php_comments

Single line comment

The (//) or hash(#) characters are used to add single line comments. Single line comment can also be referred as the inline comment. We have an example code to add single line comment on a PHP echo statement.

<?php
// Prints string data to the browser
echo "Single line comment";
?>

If we add PHP code block inside the single line comment statement, then it will truncate the comment line. For an example,

<?php
//To write a PHP program as <?php echo "Comments" ; ?> which prints Comments
?>

Multi-line comment style

We have to use /* and */ delimiters to add multi-line comments. By supporting multi-line statement in a comment line, we can add descriptive comments on our source code. We have an example for adding multi-line comment on a PHP function.

<?php
/* 
 * FUNCTION TO REPLACE WHITE SPACE as HYPHEN(-)
 * ACCEPTS STRING
 * RETURNS STRING 
 */
function replaceSpaceAsHyphen($str) {
  $newString = str_replace(" ","-",$str);
  return $newString;
} 
?>

In a multi-line comment, the nested /* and */ occurrences will truncate comment lines and cause an error.

<?php
/* 
 * FUNCTION TO REPLACE WHITE SPACE as HYPHEN(-)
 /* ACCEPTS STRING */
 * RETURNS STRING 
 */
function replaceSpaceAsHyphen($str) {
  $newString = str_replace(" ","-",$str);
  return $newString;
} 
?>

 

This PHP code tutorial was published on April 13, 2013.

↑ Back to Top