Comments in PHP
| Line comments | |
| Block comments | |
| Docblocks | |
| When to comment |
Line comments
A double slash comments out everything after it on the same line. Use it for short notes above or beside the code. The full reference lives in Comments in PHP.
// greet the visitor $greeting = "Hello!"; echo $greeting; // prints Hello!
A hash sign starts a line comment too, but the double slash is the common style.
Block comments
Slash-star pairs comment out any span of text, even across lines. They fit longer explanations and code that is paused for a while:
/* Pause the old greeting while the new one is tested. */ echo "New greeting";
Docblocks
A docblock is a block comment with two stars that documents functions and classes. Editors and tools read its tags:
/** * Build a greeting for the given name. */ function greet(string $name): string { return "Hello, " . $name . "!"; }
When to comment
Comment the why, not the what. A clear name needs no comment, but a strange limit or a workaround always deserves one:
// Shop API allows 100 calls per minute, so pause here. sleep(1);
Next: Variables and constants
Article author: Arthur Isaev