PHP Comments

Chapter 6 9 mins

Learning outcomes:

  1. What are comments
  2. Writing comments in PHP
  3. Tips for writing good comments

What are comments?

Let's make up a scenario — imagine you're working on a large, complex program in PHP and after getting done with it, you move on to another project, or better yet, go out on a vacation.

Now, after a long time, you come back to this complex program to add a new feature.

But what happens next is a wastage of many precious minutes, if not hours, in just understanding what line 15 is doing and how is the block of code in lines 389-413 working.

Worse yet, you make a change and all of a sudden, the entire code crashes — the program simply ceases to smoothly work the way it did before. The reason is a very subtle thing that you had to take care of when writing the code but forgot to, all thanks to this long break from the code.

So now what?

Well you have to start from the very first line in the program and analyze all the lines of code sequentially until you completely understand what's going on and how exactly is it going on.

Isn't there a better approach that can save this time?

Well, surely there is — use comments.

Technically speaking,

A comment is a piece of code that's ignored by the engine.

Comments aren't executed. Their main purpose is to describe some piece of code as to what it does and maybe even how it does it.

Sometimes comments are used to 'turn off' certain pieces of code, i.e. prevent them from executing until some debugging or coding in another part of the program is being done.

The world of programming could work without comments — but it couldn't last long enough. We do need some way to describe actions in complex code and thus save long hours of gazing over code (which we were once a maestro in), just trying to make intuition of it.

Let's see how to write comments in PHP.

Writing comments in PHP

In PHP, there are three ways to denote a comment:

  1. Single-line comment using #
  2. Single-line comment using //
  3. Multi-line comment using the /* and */

Let's see some quick examples.

Following, we denote a single-line comment using # (the hash symbol).

<?php

# This is a single-line comment.

A single-line comment only goes upto the end of its line. On the next line, normal code resumes unless it's also a comment.

# is simply an alias for // (two forward slashes) — they both do the exact same thing. Consider the code below, same as before, just this time replacing # with //:

<?php

// This is a single-line comment.
In other programming languages, such as JavaScript, C++, Java, single-line comments are typically denoted using //. The # symbol is used in Python to denote comments.

In contrast to this, a multi-line comment starts from /* and goes upto */. It can span as many lines as we want it to.

These kinds of comments are common in documenting code in PHP. They are used in a special documenting convention called PHP Doc. We'll cover PHP Doc in the latter part of this course.

Here's a multi-line comment:

<?php

/* This is a multi-line comment because it can
span multiple lines. We can make the comment
as long as we want it to. */

Although the code above is readable, there is a common convention used when creating a multi-line comment like this. It is as follows:

  1. First off, the comment doesn't begin on the same line where /* is written. This is to improve readability of the comment.
  2. Furthermore, at the beginning of each new line, we prepend the * symbol, aligned with the * of the starting /*, followed by the comment text for that line.
  3. Finally, after leaving a line (with the *) once the comment text ends, we terminate the comment, making sure that the * in the */ aligns with the * from previous lines.

The comment above rewritten in this commenting convention would look as follows:

<?php

/*
 * This is a multi-line comment because it can
 * span multiple lines. We can make the comment
 * as long as we want it to.
 *
 */

Doesn't this look much cleaner than the previous comment?

This convention is used heavily throughout JavaScript, C++, PHP, and many other languages.

Tips for writing comments

Knowing what comments are doesn't necessarily tell one how to write good comments. Code commenting, just like variable naming, is another art that comes with experience, time and skill.

Below are a couple of tips to consider to write pretty good comments.

Follow a convention

In languages such as PHP, where we have two ways to write comments, there are conventions devised over the years to help one decide which method to use to write a comment.

The convention of PHP is a simple one and quite a standard one:

  1. Use /* */ for documenting code. Documenting means to describe the purpose of a file, a function, a class, a method and so on.
  2. Use // for explaining code. Explaining here means to tell what a statement, or group of statements, does, and maybe even how it does it.

For example, consider the imaginary example below:

<?php

/*
 * Program 1
 * Add two numbers and print the result.
 *
 */

$x = 10;
$y = 20;

echo $x + $y;

Right at the top of the file, we document the name and purpose of the file using the /* */ comment, that is, it's called 'Program 1' and serves to add two numbers and print the result.

Since the actual code is extremely simple, there really is no need for a // comment to explain the meaning of any statement(s).

Shown below is another example:

<?php

/*
 * Leibniz-Madhava series
 *
 * Computation of an approximation of π (pi) using a
 * convergent series. 
 * 1 - 1/3 + 1/5 - 1/7 + 1/9 + ... = π/4
 *
 */

$pi4 = 0; // The value of π/4
$n = 1000; // Number of iterations
$denom = 1;

for ($i = 0; $i < $n; $i++) {
   $pi4 += (-1) ** $i * (1 / $denom);
   $denom += 2;
}

$pi = $pi4 * 4;

As before, right at the top of the file, we have a simple comment to explain what's happening in the file — computation of π through the Leibniz-Madhava series.

To learn more about this series, refer to the Wikipedia article Leibniz formula for π.

Then in the code that follows, we have two // comments to explain what the succeeding statement is doing.

You don't need to understand what exactly is happening here, but just try to understand the purpose of each of the two main types of comments in PHP — one is documenting the program while the other one is explaining stuff.

Break long comments into multiple lines.

Writing long comments is not something surprising in complex applications. Sometimes even in the simplest of applications, a short brief license notice, or copyright disclaimer put at the top is considerably long.

Putting long comments on one single line is not syntactically invalid; just not pleasing to the eye. Let's see how.

Below we construct a really long comment that spans a single line:

<?php

// This is a long long long comment that takes a long long span of words which is undesirable in PHP and all programming languages.

$x = 10;
echo $x;

See how the comment unnecessarily acts as a divider in the code rather than documenting it. It distracts our reading flow and seems as if it's not part of the code.

In this case, the example might not look that weird but if you type the code above in your editor that covers the whole screen, you'll find the comment extending out till the end of the screen, and looking extremely awful!

What one should do here is to break the comment into multiple lines, each one being a comment itself.

Let's rewrite the comment above using this approach:

<?php

// This is a long long long comment that takes a long
// long span of words which is undesirable in PHP and
// all programming languages.

$x = 10;
echo $x;

As you can see, we break the comment text after a certain number of characters. Typically, this character limit is 80.

Some code editors, the likes of Visual Studio Code, allow visual guidelines to be set up to clearly indicate such a limit.

To learn how to set up visual guidelines, referred to as rulers, in VS Code, refer to the article 4 Incredible VS Code Features That You Can't Miss! on our blog.

Try to be concise

Writing comments is useful to the programmer and others reading the code. However, writing redundantly long comments with a lot of unnecessary text can backfire — they can make code difficult to read.

When commenting code, try to be as concise as possible. Try to very briefly and neatly express the intent of the concerned piece of code.

Here's an example:

<?php

$score = '84';

// Here I am trying to convert $score to an integer.
$score = (int) $score;

The comment is clear and undoubtedly explains the purpose of the statement in line 5. However, it contains too much detail.

A much better comment would be the following:

<?php

$score = '84';

// Convert to int.
$score = (int) $score;

A long sentence condensed down to just three words, yet the underlying meaning is still intact.

Cool, isn't this?

Don't comment everything

Remember one rule of thumb: less is more!

Only comment those parts of a program that involve something that's not apparent, i.e. something that would be difficult to understand later on.

Commenting redundant pieces of code, as shown below, is useless:

<?php

$x = 10;
$y = 30;

// Print the sum of $x and $y.
echo $x + $y;

In line 7, we can easily see that we are printing the sum of $x and $y, and so the comment in line 6 is more than just useless.