How to Comment in PHP
When writing code in PHP it is good practice to make it easy to read. One aspect of this is making comments on the code to explain what something does, which makes things much easier when editing the code months down the line.
PHP offers two ways to comment out code, one to comment out the remainder of a line and another to cover multi-line blocks.
Single-Line Comments
Single line comments are added with //
(two forward slashes).
// this is a single line comment
Everything after //
will be commented out, which means you can have code in front of //
and it will be rendered.
echo 'code before comment'; // this is a comment
Muti-line Comments
Start a comment block by typing /*
(forward slash followed by an asterisk) and end it using */
(asterisk followed by a forward slash.)
/* this is a comment block
all of the text here is a comment
*/
While the above method works great for commenting out blocks it also provides a nice way to comment out in the middle of a line.
$var1 = 'foo'; /* this is a comment */ $var2 = 'bar';
Documenting PHP Code with Comments
phpDocumentor has standardised a way of documenting PHP classes and functions using DocBlocks, which are C-style comment blocks with two leading asterisks (*
). They contain a bunch of useful information about the PHP class or function.
You should use a DocBlock above certain classes and functions. It can be especially helpful to describe what the inputs and the output returned from a function are. Let's have a look at a typical DocBlock:
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
You can read more information about DockBlocks and get the full list of @tags
here.
It is also good practice to include single-line comments to describe code that isn't obvious.
public static function filesize_formatted($path)
{
$size = filesize($path);
$units = array( 'B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
$power = $size > 0 ? floor(log($size, 1024)) : 0;
// there could be a comment describing what is happening below.
return number_format($size / pow(1024, $power), 2, '.', ',') . ' ' . $units[$power];
}
Conclusion
You now know two ways of commenting out code in PHP and the best practices for documenting code using phpDocumentor. The main thing to remember is to try and stay consistent like everything with coding.