Introduction to PHP Comments
Definition
In PHP, comments are used to add notes or explanations to the code for the benefit of other developers who may read the code. Comments do not affect the functionality of the code and are ignored by the PHP interpreter when the code is executed.
The Importance of Code Documentation
Comments serve as the primary form of in-code documentation, bridging the gap between what code does and why it exists. Well-written comments can make the difference between maintainable code and technical debt. They capture the developer's intent, explain complex algorithms, warn about edge cases, and provide context that the code alone cannot convey.
Key Purposes of Comments:
- Intent Documentation: Explain why code exists, not just what it does
- Complex Logic Clarification: Break down algorithms and business rules
- Warning Markers: Highlight gotchas, assumptions, and limitations
- Development Notes: Track TODOs, FIXMEs, and technical debt
- API Documentation: Describe function parameters, return values, and usage
Types of Comments and Examples
There are two types of comments in PHP: single-line comments and multi-line comments.
Single-Line Comments
Single-line comments start with //
or #
and continue to the end of the line. For example:
// This is a single-line comment
# This is also a single-line comment
Single-Line Comment Characteristics:
- Two Syntaxes:
//
(C++ style) and#
(shell style) - Scope: From the comment marker to the end of the line
- Common Usage: Brief explanations, variable purposes, simple notes
- Placement: Can appear at the end of code lines or on separate lines
- Best Practice:
//
is more common in PHP; be consistent
Inline Comments:
$taxRate = 0.08; // 8% sales tax for this region
$total = $subtotal * (1 + $taxRate); # Calculate total with tax
Multi-line comments start with /*
and end with */
. For example:
/*
This is a multi-line comment.
It can span multiple lines.
*/
Multi-Line Comment Features:
- C-Style Syntax: Borrowed from C programming language
- Flexible Spanning: Can cover any number of lines
- Nesting Limitation: Cannot nest multi-line comments
- Common Uses: Detailed explanations, commenting out code blocks, file headers
- Formatting: Often include asterisks for visual alignment
Multi-line comments can span multiple lines and can be used to comment out large blocks of code or to add detailed explanations about the code.
DocBlock Comments
PHP also supports "Docblock" comments, which are a specific type of multi-line comment that starts with /**
and ends with */
. Docblock comments are commonly used to add documentation for functions, classes, and methods in a structured format that can be parsed by tools such as phpDocumentor.
DocBlock Standards and Benefits:
- PHPDoc Standard: Industry-standard format for PHP documentation
- IDE Integration: Modern IDEs parse DocBlocks for intelligent code completion
- Documentation Generation: Tools can create HTML/PDF documentation automatically
- Type Hinting: Provides type information for dynamic typing
- Standardized Tags: @param, @return, @throws, @deprecated, etc.
Common DocBlock Tags:
/**
* @param string $name User's full name
* @param int $age User's age in years
* @return bool True if user is adult
* @throws InvalidArgumentException If age is negative
* @deprecated 2.0.0 Use isAdult() instead
* @since 1.0.0
* @author John Doe <[email protected]>
*/
<?php
// This is a single-line comment
# This is also a single-line comment
/*
This is a multi-line comment.
It can span multiple lines.
*/
echo "Hello, world!";
/**
* This is a Docblock comment.
* It's used to document the code.
* It can be parsed by tools such as phpDocumentor
*/
function greet($name)
{
echo "Hello, $name!";
}
greet("John Doe");
?>
Code Example Analysis:
In this example, there are three types of comments: single-line comments, multi-line comments, and docblock comments.
The first two lines are single-line comments, the third line is the start of a multi-line comment, the Docblock comment is used before the function greet, the multi-line comment spans multiple lines and ends with the closing */
on the last line of the comment. The last line of the example code greet("John Doe");
is not commented and will be executed by the PHP interpreter.
Comment Parsing Behavior:
- PHP strips comments during compilation, not runtime
- Comments don't affect performance in production
- Syntax errors in comments can still cause parse errors
- Comments are preserved in source but removed from opcache
Advanced DocBlock Example
/**
* Calculate the monthly payment for a loan
*
* This function implements the standard amortization formula
* to calculate fixed monthly payments for a loan with compound interest.
*
* @param float $principal The loan amount in dollars
* @param float $rate Annual interest rate as a decimal (e.g., 0.05 for 5%)
* @param int $years Loan term in years
*
* @return float Monthly payment amount rounded to 2 decimal places
*
* @throws InvalidArgumentException If any parameter is negative or zero
* @throws LogicException If the calculation results in an invalid value
*
* @example
* ```php
* $payment = calculateMonthlyPayment(200000, 0.045, 30);
* echo "Monthly payment: $" . number_format($payment, 2);
* ```
*
* @link https://en.wikipedia.org/wiki/Amortization_calculator
* @since 1.0.0
*/
function calculateMonthlyPayment(float $principal, float $rate, int $years): float
{
// Validate inputs
if ($principal <= 0 || $rate <= 0 || $years <= 0) {
throw new InvalidArgumentException('All parameters must be positive');
}
// Convert annual rate to monthly and years to months
$monthlyRate = $rate / 12;
$months = $years * 12;
// Apply amortization formula: M = P * [r(1+r)^n] / [(1+r)^n - 1]
$payment = $principal * ($monthlyRate * pow(1 + $monthlyRate, $months))
/ (pow(1 + $monthlyRate, $months) - 1);
return round($payment, 2);
}
Comment Anti-Patterns to Avoid
Redundant Comments
// BAD: States the obvious
$count = 0; // Set count to 0
$name = trim($name); // Trim the name
// GOOD: Explains why
$count = 0; // Reset counter for new batch processing
$name = trim($name); // Remove whitespace that breaks database queries
Commented-Out Code
// BAD: Leaving dead code
// $oldMethod = true;
// if ($oldMethod) {
// processLegacy();
// }
// GOOD: Remove dead code, use version control for history
Misleading Comments
// BAD: Comment doesn't match code
// Calculate 10% discount
$discount = $price * 0.15;
// GOOD: Keep comments synchronized
// Calculate 15% bulk discount for orders over $1000
$discount = $price * 0.15;
Best Practices
Use comments to explain the purpose and functionality of the code, rather than simply describing what the code is doing.
Focus on the "why" not the "what". Code shows what happens; comments should explain why it happens. Good comments provide context, explain business rules, and clarify non-obvious decisions.
Keep comments concise and to the point. Avoid using overly verbose or redundant comments.
Every comment should add value. If you need a paragraph to explain a function, consider refactoring the code to be clearer. Concise comments are more likely to be read and maintained.
Use multi-line comments for detailed explanations, and single-line comments for brief notes or explanations.
Match comment style to content length. Single-line for quick notes, multi-line for complex explanations, DocBlocks for formal documentation. Consistency in style improves readability.
Use Docblock comments to document functions, classes, and methods in a structured format that can be parsed by tools such as phpDocumentor.
DocBlocks are investment in your code's future. They enable IDE features, automatic documentation generation, and help new developers understand your API. Always document public methods and complex internal logic.
Use comments to indicate the author of the code and the date it was written or last modified.
Authorship helps with accountability and knowledge transfer:
/** * @author Jane Smith <[email protected]> * @created 2024-01-15 * @modified 2024-02-20 Fixed calculation bug */
Keep comments up to date. If the code changes, make sure to update the comments accordingly.
Outdated comments are worse than no comments. During code reviews, verify comments match the implementation. Use refactoring tools that update DocBlocks automatically.
Use comments to indicate any known bugs or limitations of the code.
Be transparent about shortcomings:
// TODO: Optimize for datasets larger than 10k records // FIXME: Doesn't handle Unicode usernames correctly // HACK: Workaround for third-party API bug, remove after v2.0
Comment out any code that is not currently in use, rather than deleting it entirely.
Better practice: Delete unused code and rely on version control. If you must keep it, explain why:
// Temporarily disabled during migration, re-enable after 2024-03-01 // featureFlag('new_algorithm') { ... }
Use comments to indicate any assumptions or dependencies that the code has.
Document external requirements:
// Assumes MySQL 5.7+ for JSON column support // Requires php-gd extension for image processing // Expects $_SESSION['user_id'] to be set by auth middleware
Use comments to indicate any potential security risks or vulnerabilities in the code.
Security warnings are critical:
// WARNING: User input must be sanitized before using in SQL // SECURITY: This endpoint requires rate limiting // NOTE: Validates file type but not content - additional scanning recommended
Modern Documentation Practices
Type Declarations vs DocBlocks
With PHP 7+ type declarations, some DocBlock information becomes redundant:
// Redundant DocBlock
/**
* @param string $name
* @param int $age
* @return bool
*/
function isAdult(string $name, int $age): bool {
return $age >= 18;
}
// Better: Use DocBlock for additional context
/**
* Determine if a person is legally an adult
*
* @param string $name Person's full legal name for logging
* @param int $age Age in completed years
* @return bool True if age is 18 or over
*/
function isAdult(string $name, int $age): bool {
return $age >= 18;
}