PHP Comments

by Vincy. Last modified on June 29th, 2022.

Comments on source code will be useful for denoting the details of the code logic. For example, if we define a function in our program, we should add comment lines to state 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 single-line comments and multi-line comments.

Single line comment

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

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

If we add a 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 a multi-line statement in a comment line, we can add descriptive comments on our source code. We have an example for adding a 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;
}
?>

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page