05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Comments<br />

Comments give information to people who read your code, but they are ignored by<br />

<strong>PHP</strong>. Even if you think you’re the only person who will ever read your code, it’s a<br />

good idea to include comments in your code—in retrospect, code you wrote months<br />

ago can easily look as though a stranger wrote it.<br />

Good practice is to make your comments sparse enough not to get in the way of the<br />

code itself and plentiful enough that you can use the comments to tell what’s happening.<br />

Don’t comment obvious things, lest you bury the comments that describe<br />

tricky things. For example, this is worthless:<br />

$x = 17; // store 17 into the variable $x<br />

whereas this may well help whoever will maintain your code:<br />

// convert &#nnn; entities into characters<br />

$text = preg_replace('/&#([0-9])+);/e', "chr('\\1')", $text);<br />

<strong>PHP</strong> provides several ways to include comments within your code, all of which are borrowed<br />

from existing languages such as C, C++, and the Unix shell. In general, use Cstyle<br />

comments to comment out code, and C++-style comments to comment on code.<br />

Shell-style comments<br />

When <strong>PHP</strong> encounters a hash mark (#) within the code, everything from the hash mark<br />

to the end of the line or the end of the section of <strong>PHP</strong> code (whichever comes first) is<br />

considered a comment. This method of commenting is found in Unix shell scripting<br />

languages and is useful for annotating single lines of code or making short notes.<br />

Because the hash mark is visible on the page, shell-style comments are sometimes<br />

used to mark off blocks of code:<br />

#######################<br />

## Cookie functions<br />

#######################<br />

Sometimes they’re used before a line of code to identify what that code does, in<br />

which case they’re usually indented to the same level as the code:<br />

if ($double_check) {<br />

# create an HTML form requesting that the user confirm the action<br />

echo confirmation_form( );<br />

}<br />

Short comments on a single line of code are often put on the same line as the code:<br />

$value = $p * exp($r * $t); # calculate compounded interest<br />

When you’re tightly mixing HTML and <strong>PHP</strong> code, it can be useful to have the closing<br />

<strong>PHP</strong> tag terminate the comment:<br />

Then another <br />

Then another 4<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.<br />

Lexical Structure | 19

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!