Like most languages, PHP lets you add comments to your code. Comments are chunks of text that are ignored when the code is run by the PHP engine, but which are useful to programmers who need to read the code.
Now we learn how to create PHP comments, and look at some good commenting practices, including how to write and format comments effectively. You also find out how to use comments to “comment out” chunks of PHP code.

Creating a PHP comment

There are 2 basic types of PHP comments:
  • A single-line comment. This is a short comment within a single line of code.
  • A multi-line comment. This is a longer comment that can stretch over many lines.

WRITING SINGLE-LINE COMMENTS

To write a single-line comment, place either // (2 slashes) or a # (hash) before the comment:
<?php

// Here's a single-line PHP comment.
# Here's another single-line PHP comment.

?>

Note: The first comment style tends to be more popular with PHP programmers, but both styles are perfectly valid.
You can write single-line comments on their own — as just shown — or you can place a comment at
the end of a line of code:
<?php

$widgetsLeft--; // Sold another widget!

?>

Note: Everything from the comment symbol (// or #) to the end of the line is treated as a comment by the PHP engine, and is ignored.

WRITING MULTI-LINE COMMENTS

To write a multi-line comment, start the comment with /* (a slash followed by an asterisk) and end the comment with */ (an asterisk followed by a slash). Here’s an example:
<?php

/*
Here's a long PHP comment spread over
many lines.

You can format a multi-line comment
any way you like.
*/

?>

Be careful: You can’t nest multi-line comments in PHP. The following code won’t work:

<?php
/*
Here's the start of the outer comment.
/* Here's the inner comment. */
Here's the end of the outer comment.
*/

?>

This mistake is easy to make when commenting out PHP code, as described in a moment.

0 comments:

Post a Comment

 
Top
Blogger Template