Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 147 ยท Getting Started

Comments

Learn every kind of PHP comment - single-line // and #, multi-line /* */, and DocBlocks that IDEs and static analyzers read - plus the traps with ?> and #[ in PHP 8.

A comment is text in your code that PHP ignores. Comments are for people: they explain why the code does something, warn about a tricky edge case, or describe what a function expects. Six months from now, one of those people will be you.

PHP has three comment styles, and one special form, the DocBlock, that tools such as IDEs, documentation generators and static analyzers read and understand. This lesson covers all of them, two traps that catch even experienced developers, and the difference between a helpful comment and noise.

Single-line comments: // and

Two characters start a comment that runs to the end of the line: // and #. Both can sit on a line of their own or after code:

PHP Single-line comments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output is just Final price: 105. The commented-out echo doesn't run.

Both styles behave the same, but modern PHP code almost always uses //. The coding standards don't forbid #, but // is what you'll see in frameworks and libraries, and since PHP 8 a # followed by [ means something else entirely (see the next section). Pick // and stay consistent.

Tip: Most editors toggle comments with Ctrl + / (Cmd + / on macOS). It works in the editors on this site too: select a few lines and try it.

Trap 1: #[ starts an attribute, not a comment

PHP 8.0 introduced attributes, structured metadata written as #[Name] before a function, class, property or parameter. Because they start with #, PHP 8 no longer treats #[ as a comment. Old code that wrote comments like #[TODO] fix this now fails. This example breaks on purpose:

PHP #[ is not a comment in PHP 8 (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP reports a parse error instead of running anything:

TEXT
Parse error: syntax error, unexpected identifier "check" in main.php on line 4

PHP read #[TODO] as an attribute, so the words after the closing bracket became code, and an attribute must be followed by a declaration such as a function or class anyway. Writing // [TODO] check the tax rate or # TODO: check the tax rate (with a space after #) fixes it. Here is what a real attribute looks like; you'll study them in Attributes:

PHP
<?php

final class Invoice
{
    #[\Deprecated('Use totalWithTax() instead')]
    public function total(): float
    {
        return 0.0;
    }
}

Trap 2: ?> ends a single-line comment

A // or # comment ends at the end of the line or at a closing ?> tag, whichever comes first. Whatever follows the ?> is outside PHP and goes straight to the output:

PHP A closing tag inside a comment

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output is:

TEXT
Before
 and this text is printed!
After

This rule exists so that a short comment in a template like <?php // show the menu ?> doesn't comment out the HTML after it. In practice, the trap appears when a comment mentions a closing tag. Multi-line comments, covered next, don't have this behavior: inside /* */, a ?> is just text.

Multi-line comments: /* */

Everything between /* and */ is a comment, across as many lines as you like:

PHP Multi-line comments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The leading * on each inner line is purely decorative, a convention that makes the comment's extent easy to see. The last line shows that a /* */ comment can even sit in the middle of an expression, although that's rarely a good idea.

Multi-line comments don't nest

The first */ always ends the comment. If you wrap code that already contains a /* */ comment, the inner */ closes the outer comment early and the rest becomes code. This fails on purpose:

PHP Nested comments break (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

TEXT
Parse error: syntax error, unexpected token "*", expecting end of file in main.php on line 6

The comment ended at */ on line 4. PHP then read $rate = 0.1; as code and choked on the lonely */ on line 6. To disable a block of code temporarily, use your editor's toggle-comment shortcut, which puts // in front of each line. Better yet, delete the code: version control (Git) remembers it for you.

DocBlocks: comments that tools read

A comment that starts with /** (two stars) is a DocBlock. To PHP it's still a comment, but it's attached to the function, class, property or constant that follows it, and tools read its contents. DocBlocks use tags that start with @:

PHP
<?php

/**
 * Calculates the price after a percentage discount.
 *
 * The result is rounded to two decimal places.
 *
 * @param float $price   The original price.
 * @param int   $percent Discount from 0 to 100.
 *
 * @return float The discounted price.
 *
 * @throws InvalidArgumentException If $percent is outside 0-100.
 */
function applyDiscount(float $price, int $percent): float
{
    if ($percent < 0 || $percent > 100) {
        throw new InvalidArgumentException('Percent must be between 0 and 100.');
    }

    return round($price * (100 - $percent) / 100, 2);
}

The parts of a DocBlock:

  • A summary line, then an optional longer description after a blank line.
  • @param describes a parameter: its type, name and meaning.
  • @return describes the return value.
  • @throws lists exceptions the function may throw.
  • Other common tags: @var (the type of a property or variable), @deprecated, @see, @link, and @template for generics (see The PHP Type System in Depth).

Who reads DocBlocks?

  • IDEs such as PhpStorm and VS Code (with a PHP extension) show the description when you hover over a call and use the types for autocompletion.
  • Static analyzers such as PHPStan and Psalm read DocBlock types to find bugs before your code runs. They understand types PHP itself can't express, like array<int, string> (an array of strings with integer keys) or list<User>.
  • Documentation generators such as phpDocumentor build a browsable website from your DocBlocks.
  • Your own code, through Reflection. PHP keeps DocBlocks (but not ordinary comments) in memory, and getDocComment() returns them:
PHP Reading a DocBlock with Reflection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Older frameworks used this to read configuration from DocBlock "annotations" such as @Route("/home"). Since PHP 8, native attributes do that job better. You'll explore Reflection in Reflection.

DocBlocks and native types

Modern PHP has real type declarations, like float $price and : float above. When the native type says everything, repeating it in @param adds nothing. A good rule:

  • Use native types for everything PHP can check itself.
  • Add DocBlock tags only when they say more: a description, a precise type like list<string> or positive-int, or exceptions with @throws.
PHP
<?php

/**
 * @param list<string> $names Names in display order.
 */
function joinNames(array $names): string
{
    return implode(', ', $names);
}

Here array is all PHP can enforce, and the DocBlock tells tools and readers that it's a list of strings.

Writing good comments

Comments age. Code gets changed and comments often don't, so a wrong comment is worse than none. Some guidelines that hold up:

  • Explain why, not what. The code already says what it does. Say why it does it, or what isn't obvious.
  • Prefer clear names to comments. $secondsPerDay = 86400; needs no comment; $x = 86400; // seconds per day does.
  • Record decisions and warnings: a workaround for a bug in an external API, a business rule, a performance trade-off.
  • Don't leave dead code in comments. Delete it; Git keeps history.
  • Use TODO and FIXME markers consistently (// TODO: ...) so they're easy to search. Editors highlight them.
PHP Noise versus useful comments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Both lines of code are identical, but only the second comment helps the next reader. Better still, a well-named constant such as FREE_SAMPLES_PER_ORDER would carry the meaning even without a comment; you'll learn about those in Constants.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? echo 'A'; // note ?> B

    A single-line comment ends at ?>. The text after it, B with its leading space, is outside PHP and is printed.
  2. 2. In PHP 8, why does a line like #[FIXME] broken cause a parse error?

    Since PHP 8.0, #[ begins an attribute. Use // comments, or put a space after #.
  3. 3. Which comment can be read at runtime with ReflectionFunction::getDocComment()?

    Only DocBlocks (/** ... */) placed directly before a declaration are kept and attached to it. Ordinary comments are discarded.
  4. 4. What happens when you wrap code that contains /* a */ inside another /* ... */ comment?

    Multi-line comments don't nest. The first */ closes the comment, so the remaining code and the final */ are parsed as code.
  5. 5. When is a @param tag in a DocBlock most useful?

    Native types are checked by PHP. DocBlocks earn their place when they describe meaning or types PHP can't express, which static analyzers then check.

Summary

  • // and # start single-line comments; prefer //. A single-line comment ends at the end of the line or at ?>.
  • /* ... */ comments span lines but don't nest: the first */ ends them.
  • Since PHP 8, #[ starts an attribute, not a comment.
  • DocBlocks (/** ... */) before declarations use tags like @param, @return, @throws and @var. IDEs, static analyzers, documentation generators and Reflection read them.
  • Use native types first and DocBlocks for what native types can't say.
  • Good comments explain why; clear names and deleted dead code beat comments that repeat the code.

Next: Output: echo, print, printf, where you'll learn every way to send output and to inspect values while you debug.