Comments in PHP
Learning Objectives
- Master PHP programming concepts
- Write clean, maintainable code
- Apply best practices
- Build dynamic applications
Introduction to PHP Comments
Welcome to our session on PHP comments! While comments might seem like a simple or even trivial aspect of PHP, they are actually one of the most important tools in a professional developer's toolkit. Well-written comments can dramatically improve code quality, maintainability, and collaboration.
Comments in PHP are lines of code that are not executed by the interpreter. Their purpose is to explain the code, make it more readable, and provide information to developers (including your future self). As the saying goes, "Code tells you how, comments tell you why."
Analogy: If PHP code is like a novel for computers to read, comments are like the author's notes in the margins. The computer skips over these notes entirely, but they're invaluable for human readers trying to understand the author's intentions, reasoning, and the overall structure of the story.
Types of PHP Comments
PHP supports three different comment styles, each with its own specific use cases and advantages.
Single-Line Comments
Single-line comments begin with // or # and continue until the end of the line:
###CODE_BLOCK_2###
Style Note
While both // and # work for single-line comments, the double-slash // is more commonly used in PHP and is considered the standard style in most coding standards and teams. The hash # style is a legacy from Perl and shell scripting.
Multi-Line Comments
Multi-line comments start with /* and end with */. Everything between these delimiters is treated as a comment, regardless of how many lines it spans:
###CODE_BLOCK_9###
DocBlock Comments
DocBlock comments are a special type of multi-line comment that begin with /** (note the extra asterisk) and end with */. They're used for API documentation and contain structured metadata:
###CODE_BLOCK_12###
DocBlock comments are particularly important when working with documentation generators like phpDocumentor, which can automatically create API documentation from your code based on these comments.
Visual Representation of Comment Types
DocBlock Comments in Detail
DocBlock comments deserve special attention because they follow a specific structured format and are extremely valuable for code documentation.
DocBlock Structure
A typical DocBlock consists of:
- A summary (first line)
- An optional longer description
- Tags that provide metadata about the code element
###CODE_BLOCK_15###
Common DocBlock Tags
DocBlocks use a variety of tags to provide structured metadata. Here are some of the most common:
| Tag | Purpose | Example |
|---|---|---|
@param |
Documents a function parameter | @param string $username The user's login name. |
@return |
Documents a function's return value | @return boolean True if successful, false otherwise. |
@throws |
Documents exceptions that might be thrown | @throws InvalidArgumentException If the input is invalid. |
@var |
Documents the type of a property or variable | @var array List of user IDs. |
@deprecated |
Marks a function as deprecated | @deprecated since 2.3.0, use newFunction() instead. |
@since |
Documents when a function was added | @since 2.5.0 |
@see |
References related elements | @see anotherFunction() |
@todo |
Documents planned changes | @todo Add validation for email addresses. |
DocBlocks in WordPress
WordPress has its own specific DocBlock standards based on phpDoc. In WordPress development, you'll often see DocBlocks like this:
###CODE_BLOCK_32###
These detailed DocBlocks help WordPress developers understand how to use the API and track changes over time.
Practical Examples of Effective Comments
Let's look at some real-world examples of effective commenting in different contexts.
Example: Controller Method in a MVC Framework
###CODE_BLOCK_33###
In this example, the DocBlock provides a clear explanation of what the method does, while the inline comments mark the major sections of the implementation. Note that the comments focus on "why" and section organization rather than explaining obvious code.
Example: Complex Algorithm
###CODE_BLOCK_34###
For complex algorithms, comments play a crucial role in explaining the logic. This example includes:
- A DocBlock that explains what the function does and links to further information
- A step-by-step explanation of the algorithm
- Inline comments explaining the purpose of specific operations
Example: Configuration with Business Rules
###CODE_BLOCK_35###
For configuration files, comments should explain:
- Where the data comes from and when it should be updated
- Business rules or policies that are encoded in the values
- The meaning of specific values or ranges
- References to external documents or decisions
Common Commenting Patterns and Techniques
Beyond the basic syntax, there are several common patterns and techniques that can make your comments more effective.
Comment Headers for Files
File-level comments provide context for an entire file:
###CODE_BLOCK_36###
Comment Sections
For longer files, section comments help organize the code and make it easier to navigate:
###CODE_BLOCK_37###
TODO Comments
TODO comments mark incomplete work or future enhancements:
###CODE_BLOCK_38###
Many IDEs and editors recognize TODO comments and can provide a list of all TODOs in your project. Adding a ticket number or other reference makes it easier to track the work.
Debug Comments
Sometimes you need to leave comments specifically for debugging purposes:
###CODE_BLOCK_39###
Be careful with debug comments in production code. They should generally be removed or turned into more meaningful explanations before code is deployed.
Commented-Out Code
While generally discouraged, if you must comment out code temporarily, explain why:
###CODE_BLOCK_40###
Remember that version control systems like Git are a better solution for preserving old code than comments.
PHP Comments in WordPress Development
WordPress has its own specific commenting standards and practices as part of the WordPress Coding Standards. Let's explore how comments are used in WordPress development.
WordPress DocBlock Standards
WordPress follows a modified version of phpDoc standards for DocBlocks. Here's an example of a WordPress-style function DocBlock:
###CODE_BLOCK_41###
Note the WordPress-specific features:
- Multiple
@sincetags documenting when the function was added and when parameters were added or modified - Nested parameter documentation for array arguments
- Detailed return type information
WordPress Hook Documentation
WordPress uses comments to document hooks (actions and filters), which is crucial for plugin and theme developers:
###CODE_BLOCK_43###
When adding your own hooks in plugins or themes, you should follow this documentation pattern:
###CODE_BLOCK_44###
Inline Documentation in Templates
WordPress template files often use comments to guide theme developers:
###CODE_BLOCK_45###
Notice how the comments serve multiple purposes:
- The DocBlock at the top provides context for the entire file
- Inline comments explain the conditional logic
- HTML comments mark the end of important sections, making it easier to navigate complex nested structures
Tools and Tricks for Working with Comments
Modern development environments offer many tools to make working with comments more efficient.
IDE Comment Features
Most modern IDEs and code editors offer features to help with comments:
- Comment shortcuts: Keyboard shortcuts to comment/uncomment lines or blocks
- DocBlock generation: Automatic generation of DocBlock templates
- TODO tracking: Built-in lists of TODO comments across your project
- Collapsible comment blocks: Ability to collapse multi-line comments
- Syntax highlighting: Different colors for comments and code
For example, in most IDEs, you can generate a DocBlock template by typing /** and pressing Enter above a function.
Comment Tags for IDEs
Several special comment tags are recognized by IDEs to provide additional functionality:
###CODE_BLOCK_47###
Documentation Generators
Documentation generators can parse your DocBlock comments and create API documentation websites. Popular options include:
- phpDocumentor: The standard documentation generator for PHP
- Sami: A more modern documentation generator by Fabien Potencier
- ApiGen: Another PHP documentation generator
- WordPress's WP Parser: Used to generate the WordPress developer reference
These tools extract DocBlock comments and create searchable, browsable documentation websites.
Code Sniffers for Comment Standards
Code sniffers can help enforce consistent commenting standards across your codebase:
- PHP_CodeSniffer: Can validate that your DocBlocks follow standards
- WordPress Coding Standards: Includes specific rules for WordPress-style comments
- PHPStan: Can check that DocBlock types match actual types
For example, you can integrate PHP_CodeSniffer into your CI/CD pipeline to ensure all new code has proper comments.
Best Practices for Comments
To wrap up, let's summarize some best practices for using comments effectively in your PHP code.
General Principles
- Comment on "why," not "what": The code shows what happens; comments should explain why
- Keep comments updated: Outdated comments are worse than no comments
- Follow team standards: Consistency across a codebase is valuable
- Use meaningful variable and function names: Good naming reduces the need for comments
- Think of the new developer: Write comments that would help someone with no context
DocBlock Best Practices
- Document all public APIs: Functions, classes, methods, and hooks that others will use
- Include all required information: Parameters, return values, exceptions, etc.
- Be precise about types: Use accurate PHP types in @param and @return tags
- Document exceptions: Use @throws tags for all possible exceptions
- Add examples for complex APIs: Include @example tags when usage isn't obvious
Inline Comment Best Practices
- Use inline comments sparingly: Only for non-obvious code
- Place comments before the code they describe: Makes them easier to notice
- Keep comments concise: Aim for clarity and brevity
- Use consistent formatting: Same style for similar comments
- Avoid obvious comments: Don't state what is already clear from the code
Project-Level Documentation
Beyond code comments, consider these documentation practices:
- README files: Provide high-level project documentation
- CONTRIBUTING.md: Document coding standards including comment standards
- Separate documentation: For complex systems, consider dedicated documentation
- Comment templates: Provide examples of good comments for your team
Practical Exercise: Improving Comments in Code
Let's practice evaluating and improving comments in a real-world code example.
Original Code with Poor Comments
Here's a function with suboptimal comments:
###CODE_BLOCK_48###
Improved Code with Better Comments
Now let's rewrite this with better comments and code improvements:
###CODE_BLOCK_49###
Improvements Made
- Added a comprehensive DocBlock: Explains what the function does, documents parameters and return value
- Improved function and variable names: More descriptive names reduce the need for comments
- Added comments explaining "why": For example, explaining that the tax rate is based on Arizona nexus
- Used more meaningful inline comments: Comments describe the business rules, not just the obvious code operations
- Improved code organization: Better structure makes the code more readable without requiring as many comments
- Added validation: Properly check for required data
Your Turn
Try this exercise with your own code:
- Find a function or class in your codebase with minimal or poor comments
- Evaluate what's missing from the documentation
- Rewrite the comments focusing on "why" not "what"
- Add appropriate DocBlocks for functions and methods
- Consider if better naming could reduce the need for some comments
Summary and Key Takeaways
We've covered a lot of ground regarding PHP comments. Here are the key takeaways:
- Comments are for humans: They're ignored by the PHP interpreter but crucial for developers
- Three comment styles: Single-line (
//or#), multi-line (/* */), and DocBlock (/** */) - Focus on "why" not "what": Good comments explain the reasoning behind the code
- DocBlocks for documentation: Use structured DocBlocks for functions, classes, and methods
- WordPress has its own standards: Follow WordPress coding standards for WordPress development
- Tools can help: IDEs, documentation generators, and code sniffers assist with comments
- Comments need maintenance: Keep comments updated as code changes
Final Analogy: Comments in code are like road signs on a highway. Good signs don't describe what you can already see ("there's a road here"), but provide valuable context ("sharp curve ahead", "historic district", "exit for downtown"). Well-placed, informative signs make the journey smoother and safer. Too many signs create clutter and distraction, while too few leave travelers confused at critical junctions.
As you continue your PHP development journey, develop the habit of writing thoughtful, meaningful comments. Your colleagues—and your future self—will thank you for it.
Additional Resources
PHP Documentation Standards
- PSR-5: PHPDoc Standard (Draft)
- phpDocumentor: Writing DocBlocks
- WordPress PHP Documentation Standards
Books and Articles
- "Clean Code" by Robert C. Martin (Chapter on Comments)
- "Code Complete" by Steve McConnell (Section on Commenting Techniques)
- Code Tells You How, Comments Tell You Why by Jeff Atwood
Tools
- phpDocumentor - Documentation generator
- PHP_CodeSniffer - Code style checker including comment styles
- PHPStan - Static analyzer that can check DocBlock types
When and How to Use Comments Effectively
Comments are powerful tools, but they need to be used thoughtfully. Here are guidelines for when and how to use comments effectively.
What to Comment
Good comments focus on the "why," not the "what." The code itself should clearly show what it's doing; the comments should explain why it's doing it, especially when the reason isn't obvious.
Here are some specific things worth commenting:
What Not to Comment
Some types of comments can actually reduce code quality by creating noise or becoming outdated. Avoid these anti-patterns:
In general, avoid these types of comments:
Analogy: Comments should be like salt in cooking — used judiciously to enhance, not to mask poor quality. Too little, and the code lacks context; too much, and the signal gets lost in the noise.