Comments in PHP
Start a PHP comment with // or # for one line, or put it between /* and */ for several lines. PHP skips comments when it runs a script, so they never show up in the output. A one-line comment ends at the end of its line or at a ?> tag, whichever comes first.
Key facts
- PHP runs PHP code inside an HTML comment,
<!-- -->, and sends the comment to the browser. - One block comment can't hold another, because PHP ends a block comment at the first
*/it finds. - Since PHP 8.0,
#[starts an attribute instead of a comment. - A DocBlock opens with
/**and a space, tab or line break, and PHP keeps it with the declaration below it so code can read it later. - PHP prints a note written above
<?phpas plain text, because it isn't a PHP comment.
How do you write a comment in PHP?
Start a one-line comment with // or #, and put a longer one between /* and */. A comment is a note for people who read the code, and PHP ignores it.
// One ticket costs 12.
$price = 12;
# Three friends are going.
$tickets = 3;
/* Multiply the price by the number of tickets
to get the total for the group. */
$total = $price * $tickets;
echo "Total: $total\n";Total: 36
PHP read all three comments and skipped them, which is why the output holds only the total. The // and # styles make single-line comments, and /* */ makes a multi-line comment, also called a block comment.
One-line and block comments end in different places, which changes how much code each kind can hide.
| Syntax | What it is | Where it ends |
|---|---|---|
// | One-line comment, C++ style | At the end of the line or at ?> |
# | One-line comment, Unix shell style | At the end of the line or at ?> |
/* */ | Block comment, C style | At the first */ |
/** */ | DocBlock, kept with the function or class after it | At the first */ |
#[Name] | Not a comment but an attribute, since PHP 8.0 | At the matching ] |
A block comment can also sit inside a line of code, between the parts of an expression. PHP reads 12 /* ticket */ + 3 as 12 + 3.
$total = 12 /* ticket */ + 3 /* booking fee */;
echo $total;15
A one-line comment can follow code on the same line, as in echo 12; // ticket. Inside a string, though, //, # and /* are ordinary text, and echo "https://www.php.net/"; prints the whole address.
Comments that visitors post under an article are a different topic. Our commenting system tutorial builds a comment section like that with PHP, MySQL and AJAX.
How do you comment out code in PHP?
Put // in front of a line of code to switch it off. For several lines, wrap them in /* and */. Remove the markers and the code runs again.
$price = 20;
// $price = $price - 5;
echo "Price: $price\n";
/*
echo "Sale price: " . ($price - 5) . "\n";
echo "Sale ends Friday\n";
*/
echo "Done\n";Price: 20 Done
PHP skipped the line that lowers the price and both lines in the block, so the price stayed at 20. Commenting out helps while you test a change, because the old code stays where it was.
In VS Code, Ctrl+/ (Cmd+/ on a Mac) adds // in front of the code on every selected line, and the same keys take the markers away again. Use // on every line when the code you switch off already contains a block comment.
Can you nest block comments in PHP?
No. PHP ends a block comment at the first */ it finds, even when another /* opened in between. Whatever follows that */ is code again, and a leftover */ there is a parse error.
/*
echo "Step 1\n";
/* echo "Step 2\n"; */
echo "Step 3\n";
*/
echo "Done\n";Parse error: syntax error, unexpected token "*", expecting end of file in /app/main.php on line 6
The comment that line 2 opens closes at the */ on line 4, which leaves the */ on line 6 outside any comment. Not even Done appears, because PHP finds a parse error before it runs anything.
The same thing happens when the code you comment out contains */. The pattern photos/*/thumb.jpg, which the glob() function uses to list matching files, holds a */ that ends the comment early.
/*
$photos = glob('photos/*/thumb.jpg');
*/
echo "Done\n";Parse error: syntax error, unexpected string content ");" in /app/main.php on line 3
The error looks unrelated to the comment because PHP reads the rest of line 3, after the early */, as code. A // at the start of the line avoids the problem, because a one-line comment ignores any /* or */ on its line.
// $photos = glob('photos/*/thumb.jpg');
echo "Done\n";Done
What happens when a PHP block comment is never closed?
PHP stops with an Unterminated comment error when a /* has no */ after it. The message names the line where that comment starts.
echo "Start\n";
/* Tax still needs adding.
echo "End\n";Parse error: Unterminated comment starting line 3 in /app/main.php on line 3
The PHP validator flags a /* that no */ ever closes. A missing */ is harder to find when another block comment comes later, because the first comment then runs on to that comment's */.
/* Every order ships for 5.
$shipping = 5;
/* Orders over 50 get a free gift. */
$order = 60;
echo "Total: " . ($order + $shipping) . "\n";Warning: Undefined variable $shipping in /app/main.php on line 6 Total: 60
The comment from line 2 swallowed $shipping = 5;, so $shipping never got a value and the total came out as 60 instead of 65. The warning names line 6, but the fix is a */ at the end of line 2.
Why does a one-line comment stop at ?> in PHP?
A ?> tag switches PHP off, even in the middle of a one-line comment. PHP outputs everything after the tag as plain text, the same way it treats text after any other closing ?> tag.
// Type to leave PHP mode.
echo "Done\n";to leave PHP mode. echo "Done\n";
The comment ended at ?>. PHP then printed the rest of line 2 and the code on line 3 as text. On a website, that code would end up in the page that visitors receive.
A block comment doesn't stop at ?>, because it ends only at */. Use /* and */ for any note or line of code that contains ?>.
/* Type ?> to leave PHP mode. */
echo "Done\n";Done
Do HTML comments stop PHP code from running?
No. PHP doesn't treat <!-- and --> as a comment, so it outputs them as text and runs any PHP between them.
<p>Welcome</p>
<!-- echo "Draft text"; --><p>Welcome</p> <!-- Draft text -->
A browser doesn't display an HTML comment, but the comment still reaches the visitor, and anyone can read it in the page source. To hide PHP code, comment it out inside the PHP tags.
<p>Welcome</p>
// echo "Draft text";
<p>Thanks for visiting</p><p>Welcome</p> <p>Thanks for visiting</p>
Nothing from the PHP comment reaches the output. The line break right after ?> disappears too, which is why the two paragraphs sit on neighboring lines.
Is #[ a comment in PHP 8?
No. Since PHP 8.0, #[ starts an attribute, so a # comment that begins with [ is no longer a comment.
An attribute is a label in square brackets that adds information to a function, class or other declaration. A note such as #[todo] was a plain comment before PHP 8.0, and PHP now reads it as an attribute.
] Check the tax rate.
echo "Done\n";Parse error: syntax error, unexpected identifier "Check" in /app/main.php on line 2
PHP read #[todo] as an attribute and then found the word Check, which can't follow one. Put a space after the #, or use //, and the note is a comment again.
# [todo] Check the tax rate.
// #[todo] is fine inside a // comment.
echo "Done\n";Done
Right above a function, #[todo] causes no error at all. PHP attaches it to the function as an attribute named todo, so the note quietly stops being a comment. The PHP 8.0 migration notes list this change.
What is a DocBlock in PHP?
A DocBlock is a block comment that starts with /** and describes the code right below it. It's also called a doc comment or a PHPDoc comment.
A function is a named piece of code that runs when you call its name, and functions get their own lessons later in the course. In a DocBlock above a function, tags such as @param and @return describe what the function takes and what it gives back.
/**
* Adds the booking fee to a ticket price.
*
* @param int $price The ticket price.
* @return int The price with the fee added.
*/
function withFee($price)
{
return $price + 3;
}
echo withFee(12);15
The DocBlock doesn't change what withFee() does. PHP doesn't check its tags either, so @param int won't stop a call that passes text instead of a number.
What reads a DocBlock in PHP?
Your code can read a DocBlock through Reflection, the part of PHP that inspects code. PHP keeps a DocBlock that sits above a function or class for this, while other comments are gone once PHP has read the file.
/** Adds the booking fee. */
function withFee($price)
{
return $price + 3;
}
/* Adds the sales tax. */
function withTax($price)
{
return $price * 1.2;
}
var_dump((new ReflectionFunction('withFee'))->getDocComment());
var_dump((new ReflectionFunction('withTax'))->getDocComment());string(28) "/** Adds the booking fee. */" bool(false)
Each var_dump() line asks PHP for the DocBlock of one function. The new keyword creates a ReflectionFunction helper for the function named in the quotes, and -> calls one of the helper's methods, the functions that belong to it.
The getDocComment() method returns the DocBlock, or false when there is none, as for the plain /* comment above withTax().
A DocBlock also needs a space, tab or line break right after /**, which is why PHP treats /**Adds the fee.*/ as a plain comment.
Code that reads DocBlocks while it runs needs PHP to keep them. OPcache, the part of PHP that keeps compiled scripts in memory, throws DocBlocks away when its opcache.save_comments setting is off, which can break that code.
The PHP minifier can strip comments from a file, and its Keep docblocks option leaves DocBlocks in place for code that reads them.
PHP 8.6 adds DocBlocks for individual function parameters, read with a new getDocComment() method of ReflectionParameter. The runner can't run that feature, because it uses PHP 8.5.12, which doesn't have the method.
Do comments slow down PHP?
Comments add no time once a script is running. PHP leaves them out of the instructions it compiles, and in our PHP 8.6.0 test, reading 2,000 comment lines added less than 0.2 milliseconds to loading the file.
What should a comment in PHP say?
A good comment says why the code does something, since the code already shows what it does. // Take 5 off. repeats the code under it, while // Members get 5 off. tells the reader something the code can't.
Update a comment when you change the code it describes, because a wrong comment misleads the next reader. Once you're sure you won't need commented-out code, delete it before old lines pile up.
Common mistakes with comments in PHP
In most PHP comment mistakes, the comment ends somewhere other than you meant.
- Parse error: syntax error, unexpected token "*", expecting end of file. A block comment sits inside another one, so its leftover
*/is read as code. Comment out each line with//instead. - Parse error: Unterminated comment starting line 3. The
/*on the line the message names has no*/. Add one where the comment should end. - Part of a comment, or the code after it, shows up in the output. A
//or#comment contains?>, which switched PHP off. Use/*and*/for that note. - A comment above
<?phpshows up in the output. Comments work only inside the PHP tags, and PHP outputs any text before<?phpas it is. Move the comment below the tag.
Exercise
Comment out the line that prints Discount: 5 without deleting it. The script should then print Price: 20 and Total: 15. Also add a comment below <?php that says what $price holds, on the line above $price = 20; or at the end of that line.
$price = 20;
$discount = 5;
echo "Price: $price\n";
echo "Discount: $discount\n";
echo "Total: " . ($price - $discount) . "\n";Price: 20 Total: 15
Show the solution
// The price of one item before the discount.
$price = 20;
$discount = 5;
echo "Price: $price\n";
// echo "Discount: $discount\n";
echo "Total: " . ($price - $discount) . "\n";Quiz
This quiz has 5 questions. Pick an answer to see why it is right or wrong.
-
1What does this script print?
echo "a"; // note bThe comment stops at ?>, which switches PHP off, so the b after the tag is plain text that PHP outputs. Printing only a would need the comment to run to the end of the line, but a one-line comment always stops at ?>.
-
2What does this script print?
echo 1 + /* 2 + */ 3;PHP skips everything between /* and */ and adds only 1 and 3. A block comment can sit in the middle of a line of code, which is why this runs without an error and the 2 never counts.
-
3What happens when this script runs?
/* echo "A\n"; /* echo "B\n"; */ */ echo "C\n";The comment from line 2 ends at the first */, on line 4, so the */ on line 5 is left over as code. PHP finds that parse error before running anything, which is why even C never appears.
-
4What does this script print?
<!-- echo "Hi"; -->PHP doesn't treat <!-- and --> as a comment, so it outputs them as text and runs the echo between them. A browser would hide the result from view, but Hi is still there in the page source, so the output isn't empty.
-
5Inside a PHP block, which of these lines is a comment in PHP 8.6?
With a space after the # sign, the line is an ordinary one-line comment. Without the space, #[ starts an attribute, so PHP 8.6 stops with a parse error on that line.























