This tutorial will teach you how to use PHP comments to document your code.
Comments are critical components of the code. Comments contain useful information that will aid you and other developers in understanding the meaning of the code later on.
PHP recognises two types of comments:
- Single line Comments
- Comments on multiple lines
Single Line Comments
The one-line comment is placed at the end of the line or at the current block.
A one-line comment starts with the pound (
#) or double forward-slash (
//). The rest of the text after the (//) is ignored by the PHP interpreter.
The following example uses the // for a one-line comment:
<?php $rate = 100; $hours = 173; $payout = $hours * $rate; // payout calculation
And in the following example, the # is used for a one-line comment:
<?php $title = 'PHP comment'; # set default title
Multiline Comments in PHP
A multi-line comment is one that begins with /* and ends with */. As an example:
<?php /* This is an example of a multi-line comment, which can span multiple lines. */
When you need to span numerous lines in a comment, you use the multi-line comment.#
Best practises for Comments in PHP
Use the following rules to correctly document your code:
1) Using meaningful identifiers to make the code speak for itself without the use of comments. You can use the following as an example:
$is_completed = true;
Instead of a mysterious name accompanied by a comment:
$ic = true; // is completed
The code itself can serve as helpful comments.
2) Instead of writing a comment to explain what the code does, explain why it does it. Consider the following scenario:
// complete the task $is_completed = true
3) Try to be as brief and precise as possible when posting a comment.