PHP Comments
Comments are notes written inside the code. PHP ignores them completely, so they do not change how the program works. They help you and other developers to understand the code later, and you can also use them to stop a piece of code from running for a while.
Single line comments
A single line comment starts with // or # and continues until the end of the line. You do not need to close it.
Multi line comments
A multi line comment starts with /* and ends with */. You must close it. Everything between them is ignored, even many lines.
<?php
// This is a single line comment
# This is also a single line comment
echo "Hello World!"; // a comment after the code
/*
This is a multi line comment.
echo "This line will not run";
*/
?>
Output:
Hello World!
Doc comments
A comment that starts with /** is a doc comment. It is used to describe a function or class, and editors like VS Code and PhpStorm show it as a hint when you use that function.
<?php
/**
* Adds two numbers.
*
* @param int $a First number
* @param int $b Second number
* @return int The sum
*/
function add($a, $b) {
return $a + $b;
}
echo add(2, 3);
?>
Output:
5
Comment out code while testing
Comments are a quick way to disable some code without deleting it.
<?php
echo "Line 1<br>";
// echo "Line 2<br>";
echo "Line 3";
?>
Output:
Line 1
Line 3
Good practice for comments
- Explain why the code does something, not what is obvious from the code.
- Keep the comments short and update them when the code changes.
- Do not leave old commented code in the final project, remove it.
- In PHP 8,
#[starts an attribute and not a comment, so write#with a space if you use hash comments.
Comments are part of the basic PHP syntax.
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| What is single line comment in PHP? Explain with syntax. |