It’s important to comment your PHP code. Code has a habit of making sense at the time you write it, then looking like a mess in 3 months’ time! If you add comments at the time you write your code then you will find that your code is a lot more readable when you (or another developer) return to it later.
A comment should explain what a chunk of code does, or is intended to do. Here are some good examples:
<?php
if ( $widget->stockLeft == 0 ) $widget->delete(); // Remove the widget if it's sold out

// Show only recent articles
for ( $i=0; $i < count( $articles ); $i++ ) {
if ( time() - $articles[$i]->pubDate < (86400 * 7) ) $articles[$i]->displayTitle();
}

?>

FORMATTING COMMENTS

It’s good to format your comments to make them easy to read. The following PHP comments are hard to read due to bad formatting:
<?php

// Retrieve all widgets
$widgets = Widget::getAll();
/*Update all the widgets in the database,
changing each widget's quantity*/
for ( $i=0; $i < count( $widgets ); $i++ ) {
$widgets[$i]->quantity += $widgets[$i]->getNewStock(); //Set the quantity
$widgets[$i]->update(); //Update the widget
}

?>

These comments, on the other hand, are much easier on the eye:

<?php

// Retrieve all widgets
$widgets = Widget::getAll();

/*
Update all the widgets in the database,
changing each widget's quantity
*/

for ( $i=0; $i < count( $widgets ); $i++ ) {
$widgets[$i]->quantity += $widgets[$i]->getNewStock();   // Set the quantity
$widgets[$i]->update();                                  // Update the widget
}

?>

COMMENTING OUT PHP CODE

You can use PHP comments to “comment out” (temporarily disable) chunks of code. This can be useful when debugging your PHP scripts:
<?php

/*
if ( $widget->stockLeft == 0 ) $widget->delete(); // Remove the widget if it's sold out

// Show only recent articles
for ( $i=0; $i < count( $articles ); $i++ ) {
if ( time() - $articles[$i]->pubDate < (86400 * 7) ) $articles[$i]->displayTitle();
}
*/

?>

However, be careful when commenting out PHP code containing multi-line comments. Since you can’t nest multi-line comments in PHP, the following won’t work:

<?php
/*
/*
Update all the widgets in the database,
changing each widget's quantity
*/

for ( $i=0; $i < count( $widgets ); $i++ ) {
$widgets[$i]->quantity += $widgets[$i]->getNewStock();   // Set the quantity
$widgets[$i]->update();                                  // Update the widget
}
*/

?>

0 comments:

Post a Comment

 
Top
Blogger Template