Do you feel good looking at PHP projects with thousands of classes, and functions without knowing what they do? Or even just a few lines of codes but you quickly forgot what the previous lines do? Well, I did. That’s why you should know how to write PHP comments, and – I mean, do it the right way.

TL;DR

You can quickly write PHP comments by three methods:

  • Use double forward slashes: //
    This method is only used for single-line comments.
  • Forward slash and asterisk – Block type: /* (open) and */ (close)
    This method can be used for both single-line and multiline comments.
  • Use hash sign: #
    Similar to forward slashes, this method can be used for single-line comments.

Quick PHP comments example:

PHP

And the comment won’t be outputted to the user:

PLAINTEXT

That’s all the basic tips you need for writing PHP comments.

Below are other tips to know for getting your PHP comments written properly, and following PHP coding standards.

What are PHP comments and why should we write comments?

Like any other programming language, PHP comment helps organize your PHP project code structure for better understanding and debugging purposes, and also adds explanation and clarification to the other PHP developers looking at your code.

For example, do you want your PHP codes (or somebody’s codes) to look like this?

PHP

Or should it be like this?

PHP

Of course, these are just dummy codes, but imagine a project with thousand of lines of codes, functions, classes, it would be a real nightmare without any comments to tell the developer what is everything.

Having clear PHP comments is highly recommended, especially in your public GitHub projects, or company/team PHP projects which is a must.

Best practices to write PHP comments

Although PHP comments can be written the way you preferred, to follow PHP coding standards and make it developer friendly, there are several recommended guidelines when writing comments in PHP projects:

1. Use forward slashes // for single-line comments

Single-line comments should be used by forward slashes method:

PHP

2. Use forward slash + asterisk (block type) /* */ for multiline comments

Multiline comments should be used by slash + asterisk method:

PHP

3. Use block type /* */ for header comments

Header comments are the starting comments of a PHP file to clarify the content to the developer.

PHP

4. Use block type /* */ as DocBlock format to document PHP functions and classes

DocBlock is an adaptation of Javadoc for PHP programming, it allows external document generators and PHP IDEs to interpret variable types for providing code completion, type hinting, and debugging.

PHP

5. Comments should be on their own line

PHP

That’s all about general recommendations and tips for writing PHP comments in PHP development. This article could be updated later in case of new information, or when it should be revised.

Happy coding!