PHP Comments

Created with Sketch.

PHP Comments

Summary: in this tutorial, you’ll learn how to use PHP comments to document your code.

Comments are important parts of the code. Comments provide useful information that will help you and other developers understand the meaning of the code more quickly later.

PHP supports two types of comments:

  • One-line comments
  • Multi-line comments

One-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

Code language: HTML, XML (xml)

And the following example uses the # for a one-line comment:

<?php

$title = 'PHP comment'; # set default title

Code language: HTML, XML (xml)

Multi-line comments

A Multi-line comment start with /* and end with */. For example:

<?php
/*
This is an example of a multi-line comment,
which can span multiple lines.
*/

Code language: HTML, XML (xml)

In practice, you use the multi-line comment when you need to span comments multiple lines.

Writing meaningful comments

To document your code effectively, you use the following guidelines:

1) Making the code speak for itself without using comments by naming meaningful identifiers. For example, you can use the following:

$is_completed = true;

Code language: PHP (php)

Instead of using a cryptic name with a comment:

$ic = true; // is completed

Code language: PHP (php)

The code itself can be good comments.

2) Don’t write a comment to explain what code does, instead, explain why it does so. For example:

// complete the task
$is_completed = true

Code language: PHP (php)

3) When writing a comment, make it as concise as possible.

Summary

  • Comments are important parts of the code because they explain why code does what it is supposed to do.
  • PHP supports both one-line and multi-line comments.
  • A one-line comment starts with the # or // .
  • A multi-line comment starts with /* and end with */.

Leave a Reply

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