PHP Comments.

This is a simple tutorial on how to write comments in PHP. In PHP, there are three common ways (or styles) to add comments to your source code.

Double forward-slash.

The double forward-slash comment is useful whenever you want to write a single-line comment. An example:

<?php

//This is a comment.
echo 'How to write comments in PHP.';

This is sometimes referred to as a C++ style comment. This style is better for one-liners. i.e. small tidbits of information. If you intend on writing a lengthy explanation for your code, then you will probably want to use the next style.

Multi-line.

The multi-line comment starts with a forward-slash and an asterix symbol / star, before ending with an asterix and forward-slash (the order is important). This style is typically used whenever the code in question requires a lengthier explanation.

An example of the multi-line C-style comment being used:

<?php

/* This is just an example of a 
   multi-line comment being used in PHP.
*/
$obj->myFunction();

Shell style.

The shell (aka Perl) style starts with a hash symbol. This is also a one-liner. There is no difference between this style and the C+ double-slash style that was shown in the first example.

An example of the shell style:

<?php

#Get user posts.
$posts = $user->getPosts();

As you can see – the hash symbol and the double-slash are the exact same. It all comes down to the developer’s preference.

API Documentation.

In many cases, you will come across DocBlocks. These are multi-line comments that use special tags such as @return, @param and @author. These DocBlocks typically follow the PHPDoc Standard, as phpDocumentor is a popular tool that gives developers the ability to generate API documentation for their PHP code. An example of a DocBlock-style being used to describe a PHP function:

/**
  * Retrieve a user's comments.
  *
  * @param $userId int The user's ID.
  * @return array Returns an array.
  */
 function getUserComments($userId){
     //Do something
 }