PHP 8 Beginner Language Basics · 7 min read

PHP Comments: Line, Block, and Docblocks

Lesson 2 of 43 in the PHP 8 learning path.

How do I comment PHP without commenting out the wrong lines?

Comments are notes for the next reader of a grade-book class. They are removed before the script runs, so they can explain a passing line or a parameter without changing the score a student receives. PHP offers three forms you will actually use: a line comment that starts with // and runs to the end of the line, a block comment that starts with /* and ends at the next */, and a docblock that starts with /** and describes a class or function for people and for static analysis.

The sample puts a docblock on the class and on summary(), a line comment on the passing threshold, and a block comment beside the status choice. The return statement stays outside every comment, which is the rule that prevents a mistyped closer from swallowing live code. A docblock can list the integer range for a score, and the constructor still enforces that range in real code.

Syntax & Parameters

Syntax
// line comment
/* block comment */
/** Docblock for a class, method, or function. */

Example

src/Notes.php
<?php

declare(strict_types=1);

/**
 * One graded attempt stored for the class record.
 */
final class AttemptNote
{
    /**
     * @param int $score Points earned, from 0 through 100.
     * @param string $studentName Display name already trimmed by the caller.
     */
    public function __construct(
        private readonly int $score,
        private readonly string $studentName,
    ) {
        if ($score < 0 || $score > 100) {
            throw new InvalidArgumentException('Score must be between 0 and 100.');
        }
    }

    public function isPassing(): bool
    {
        // 75 is the passing line on this grade book.
        return $this->score >= 75;
    }

    /**
     * Describes the attempt for the enrollment roster.
     */
    public function summary(): string
    {
        /*
         * Keep this block on the explanation.
         * The status assignment below has to run.
         */
        $status = $this->isPassing() ? 'passing' : 'scheduled for a retake';

        return $this->studentName . ' scored ' . $this->score . ' (' . $status . ').';
    }
}

$passing = new AttemptNote(88, 'Amina Cruz');
echo $passing->summary() . "\n";
echo 'passing=' . ($passing->isPassing() ? 'yes' : 'no') . "\n";

$retake = new AttemptNote(71, 'Luis Navarro');
echo $retake->summary() . "\n";
echo 'passing=' . ($retake->isPassing() ? 'yes' : 'no') . "\n";

Expected Output

Amina Cruz scored 88 (passing).
passing=yes
Luis Navarro scored 71 (scheduled for a retake).
passing=no

Line-by-Line Walkthrough

  1. declare(strict_types=1) applies to calls made from this file, including the two AttemptNote constructions at the bottom.
  2. The class docblock says what the object represents in the class record, and it is not executed.
  3. The constructor docblock records the legal range for $score, and the if statement below it actually rejects values outside 0 through 100.
  4. Promoted readonly properties keep the score and the name on the object without a separate assignment block.
  5. isPassing() uses a line comment to name the threshold 75, then returns the comparison so the comment cannot hide the return.
  6. summary() opens a block comment, closes it, and only then assigns $status, so the assignment remains live code.
  7. The ternary chooses passing or a retake from isPassing(), which keeps the threshold in one method.
  8. The return concatenates the student name, the score, and the status into one roster sentence.
  9. Amina Cruz is constructed with 88, which is at or above 75, so the echoes report passing and yes.
  10. Luis Navarro is constructed with 71, so the same methods report a retake and passing=no.

Common Pitfalls & Security

A comment that never closes, or that closes too early, changes which lines PHP executes. That is a logic bug, and it becomes a security bug when the swallowed lines were the authorization check or the output encoding. Treat comments as text that must stay off the live path. Docblocks are still comments: a @param line does not validate input.

  • A block comment ends at the first */. A second closer later in the file leaves the lines after the first closer running, often with a confusing parse error.
  • Unsafe anti-pattern (do not ship): wrapping a password check or an escape call in /* */ during a quick test and committing that file.
  • # starts a line comment too. // is the form most PHP code uses, and # is easy to misread as a shell prompt in a mixed document.
  • Nested block comments do not exist. /* outer /* inner */ ends at the first closer, and the word outer is then parsed as code.
  • Comments are stripped from execution and are not an access-control mechanism. Anyone with the source can read them, so they are the wrong place for a database password.
  • An outdated comment that names the old passing line of 70 will be trusted by the next editor. Update the comment in the same change as the comparison.

Best Practices & Modern Standards

On PHP 8.3 and newer, write the rule in the type system and in executable checks, then use a docblock for the part the signature cannot say, such as the meaning of a score range. A readonly property and a return type already tell the reader the shape of the data. The comment should say why 75 is the passing line for this grade book.

Prefer // for a single line and /** */ for public methods. Keep /* */ short and visually closed before the next statement. When a block of code is wrong, delete it or replace it in version control. A commented-out copy of the old algorithm rots and invites someone to uncomment the weaker path.

Real-World Use

The grade book stores an AttemptNote for each quiz. The docblock tells the next instructor that 0 through 100 is the accepted range, the line comment records that 75 is the passing line for this term, and summary() prints a roster sentence. A registrar reading the class file can see the policy without running the script, and the returns still execute because they sit outside the comments.

Frequently Asked Questions

Do comments slow down a request?

The runtime does not execute them. They add a tiny amount of source to parse. Write the comments a future editor needs, and do not worry about the cost of a handful of lines on a grade-book request.

Can I nest a block comment inside another block comment?

No. The first */ closes the comment that is currently open. The text after that closer is PHP again, which usually produces a parse error or, worse, runs a statement you thought was hidden.

Does a docblock enforce the @param type?

No. A docblock is documentation. declare(strict_types=1), parameter types, and the constructor check are what reject a bad score. Keep the docblock accurate so it matches those checks.

Should passwords or keys appear in comments?

No. Comments ship with the source and show up in backups and pull requests. Name the environment variable the password comes from, and keep the secret itself out of the file.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…