A comment is a note for humans. PHP skips it completely. Comments help you remember why you wrote something, and they help the next person who reads your code.
Single-line comments
Use // or #. Everything after it on that line is ignored.
<?php
// This is a comment
echo "Hello"; // A comment after code
# This style works too, but // is more common
echo " World";
Hello World
Multi-line comments
Start with / and end with /.
<?php
/*
This comment
runs over several lines.
*/
echo "Done";
Done
DocBlocks
A DocBlock is a special multi-line comment that starts with /**. Editors read it to show help for a function.
<?php
/**
* Adds two numbers.
*
* @param int $a First number
* @param int $b Second number
* @return int
*/
function add(int $a, int $b): int
{
return $a + $b;
}
echo add(2, 3);
5
Turn code off with a comment
Comments are also a quick way to disable a line while you test.
<?php
echo "One\n";
// echo "Two\n";
echo "Three\n";
One
Three
What makes a good comment
Explain the why, not the what. The code already says what it does.
// Bad: says what the code already says
$count = $count + 1; // add one to count
// Good: says why
$count = $count + 1; // the header row is not part of the data