login

PHP Comment

PHP comment is a very important part of the code. Comments make the code easier to read and maintain.  PHP supports two style of comments:

  • Single line comments
  • Multiline comments

Single line comment is used for a quick note of a line of code and start with //. Let's take a look at an example using single line comment:

<?php
    $payout = $x * $y; // payout calculation
?>

In the above example, single line comment starts with // and comment text.

Multiline comment is used to describe something in a greater depth such as complicated algorithm,  business logic. Multiline comment starts with /* and end with */. Here is an example of using multiline comment.

<?php 
function get_age($birth_date)
{
/*
 - find the difference between current year and year of birth
 - check if date_of_birth has not occurred this year yet, minus the age by 1
*/
        

        list($year_of_birth,$month_of_birth,$date_of_birth) = explode("-", $birth_date);



        $age = date("Y") - $year_of_birth;

        $month_diff = date("m") - $month_of_birth;

        $day_diff = date("d") - $date_of_birth;


        if ($day_diff < 0 || $month_diff < 0)

          $age--;

        return $age;

}
?>

In the above example, the multiline comment is used to explain the logic of calculating age based on a given date of birth.

Be noted that PHP comment resides in PHP code file but PHP Interpreter does not output the PHP comments.

Tips on writing comment effectively

  • Comment should be used to tell how a piece of code does instead of how it works.
  • Comment is also written to helps other developers who maintains the code later easier to understand the code.