PHP Comments

Documenting and explaining your PHP code

💬 PHP Comments

Comments are notes in your code that PHP ignores during execution. They help explain code logic, document functions, and make code readable for yourself and other developers.


<?php
// This is a comment
echo "Hello World!"; // This code runs
?>
                                    

Output:

Hello World!

Types of Comments

//

Single-Line Comments

Use double slashes (//) for brief notes on one line. Everything after // on that line is ignored by PHP.

<?php
// This is a comment
echo "Hello"; // Inline
?>
#

Hash Comments

Use hash symbol (#) for single-line comments. Works exactly like // but less common in PHP. Borrowed from Perl and Shell scripting.

<?php
# This is also a comment
echo "Hello"; # Works too
?>
/* */

Multi-Line Comments

Use /* to start and */ to end comments spanning multiple lines. Perfect for longer explanations, documentation, or temporarily disabling code blocks.

<?php
/* This comment
   spans multiple
   lines */
?>
/**

DocBlock Comments

Special multi-line comments starting with /** used for documentation. Describe functions, classes, and parameters. Tools can generate documentation from these.

<?php
/**
 * Function description
 * @param string $name
 */
?>

🔹 Single-Line Comments

Using // and # for brief explanations:


<?php
// This is a single-line comment
echo "Hello World!";

# This is also a single-line comment
echo "PHP is fun!";

// You can explain what the code does
$price = 100;  // Store the price

// Comments can be on their own line
// Or at the end of a code line

echo "Total: $price";  // Display the price
?>
                            

Output:

Hello World!PHP is fun!Total: 100

🔹 Multi-Line Comments

Using /* */ for longer explanations:


<?php
/*
This is a multi-line comment.
It can span multiple lines.
Useful for longer explanations.
*/

echo "Hello!";

/*
You can use it to explain complex logic:
- First, we calculate the total
- Then, we apply the discount
- Finally, we display the result
*/

$total = 100;
$discount = 10;
$final = $total - $discount;

echo "Final price: $final";

/* 
Multi-line comments are also useful
for temporarily disabling code:

echo "This won't run";
echo "Neither will this";
*/
?>
                            

Output:

Hello!Final price: 90

🔹 DocBlock Comments

Professional documentation for functions and classes:


<?php
/**
 * Calculate the area of a rectangle
 * 
 * This function takes length and width as parameters
 * and returns the calculated area.
 * 
 * @param float $length The length of the rectangle
 * @param float $width The width of the rectangle
 * @return float The calculated area
 */
function calculateArea($length, $width) {
    return $length * $width;
}

// Use the function
$area = calculateArea(10, 5);
echo "Area: $area";

/**
 * User class for managing user data
 * 
 * @author John Doe
 * @version 1.0
 */
class User {
    /**
     * @var string User's name
     */
    public $name;
    
    /**
     * Constructor
     * @param string $name The user's name
     */
    public function __construct($name) {
        $this->name = $name;
    }
}
?>
                            

Output:

Area: 50

🔹 Best Practices for Comments

Guidelines for writing effective comments:

✅ Good Comment Practices:

  • Explain WHY, not WHAT: Code shows what it does, comments explain why
  • Keep comments updated: Update comments when you change code
  • Be concise: Short, clear comments are better than long essays
  • Use proper grammar: Write complete sentences with punctuation
  • Comment complex logic: Explain tricky algorithms or business rules

❌ Avoid These Comment Mistakes:

  • Obvious comments: Don't state what's already clear from code
  • Outdated comments: Remove or update comments that no longer apply
  • Commented-out code: Delete unused code instead of commenting it
  • Too many comments: Over-commenting makes code harder to read

🔸 Good vs Bad Comments


<?php
// ❌ BAD: Obvious comment
$total = $price + $tax;  // Add price and tax

// ✅ GOOD: Explains business logic
$total = $price + $tax;  // Tax is included per state law

// ❌ BAD: Stating the obvious
// Loop from 1 to 10
for ($i = 1; $i <= 10; $i++) {
    echo $i;
}

// ✅ GOOD: Explains purpose
// Generate invoice line items for the report
for ($i = 1; $i <= 10; $i++) {
    echo $i;
}

// ❌ BAD: Commented-out code
// $oldPrice = 50;
// echo $oldPrice;

// ✅ GOOD: Explain complex calculation
// Apply progressive discount: 10% for orders over $100, 
// additional 5% for orders over $500
if ($orderTotal > 500) {
    $discount = 0.15;
} elseif ($orderTotal > 100) {
    $discount = 0.10;
}
?>
                            

🔹 Commenting for Debugging

Use comments to temporarily disable code while testing:


<?php
// Testing different approaches

// Approach 1: Simple calculation
$result = $price * 1.1;

// Approach 2: More detailed (currently testing)
/*
$basePrice = $price;
$taxRate = 0.1;
$result = $basePrice * (1 + $taxRate);
*/

echo "Result: $result";

// TODO: Implement discount logic
// FIXME: This calculation doesn't account for bulk discounts
// NOTE: Tax rate may vary by state

/*
Temporarily disabled for testing:

if ($quantity > 100) {
    $discount = 0.2;
} else {
    $discount = 0.1;
}
*/
?>
                            

Output:

Result: 110

🔹 Practical Comment Example

A well-commented PHP script:


<?php
/**
 * Simple Shopping Cart Calculator
 * Calculates total price with tax and discount
 * @version 1.0
 */

// Product information
$productName = "Laptop";
$price = 1000;
$quantity = 2;

// Calculate subtotal
$subtotal = $price * $quantity;

// Apply discount for bulk orders (10% off for 2+ items)
if ($quantity >= 2) {
    $discount = $subtotal * 0.10;
} else {
    $discount = 0;
}

// Calculate price after discount
$afterDiscount = $subtotal - $discount;

// Add sales tax (8%)
$tax = $afterDiscount * 0.08;

// Calculate final total
$total = $afterDiscount + $tax;

// Display results
echo "<h2>Order Summary</h2>";
echo "<p>Product: $productName</p>";
echo "<p>Quantity: $quantity</p>";
echo "<p>Subtotal: $$subtotal</p>";
echo "<p>Discount: -$$discount</p>";
echo "<p>Tax: $$tax</p>";
echo "<p><strong>Total: $$total</strong></p>";

// TODO: Add shipping calculation
// NOTE: Tax rate should be configurable per state
?>
                            

Output:

Order Summary

Product: Laptop

Quantity: 2

Subtotal: $2000

Discount: -$200

Tax: $144

Total: $1944

🧠 Test Your Knowledge

Which symbol starts a single-line comment in PHP?