Jump to content
xisto Community
vujsa

PHP: Good Comments Make Good Scripts Commenting makes scripts easier to write

Recommended Posts

So this is a basic programing tool that is too often overlooked.

I learn programing by looking at other peoples work and figuring out what each command does. Having comments in the code provides me with an idea of what the author was thinking while writing that part of the code.

 

Additionally, commenting your code allows the code to be modified by others for uses other than what it was originally written for. This type of versitility makes the overall value of the script higher. Many programmers believe that they should protect their scripts by intentionally making them difficult to read. This actually makes the scripts less desireable because fewer people can modify or fix such scripts.

 

So I'd like to take this opportunity to explain how to comment your code, when to comment your code, and what comments you should make.

 

PHP comments are made with a double slash // preceeding the comment.

<?// PHP comment goes here.?>

The double slash is only good for one line of code so new double slashes are needed for each line of comment.

<?// If one line of commenting is no enough or undesirable,// a second line can be added this way.?>

The double slash has yet another use. a comment can exist on the same line as the code which it describes as long as the comment comes after the PHP code.

<?// Let's add some valid PHP code below such as a variable assignment.$foo = "foo_value";             // the value of $foo is "foo_value".?>

While the double slash is the commenting method devoloped for PHP, the double slash is not the only commenting tag that PHP will allow.

 

Perl users will be happy to know that shell comment tags are welcome as are C program comment tags.

 

The pound sign # is used for comments in shell programs like Perl and are used the same way as the PHP double slash. The comment follows the pound sign, a pound sign is only good for one line of comment, and a comment can share the same line as code as long as the comment comes after the code.

<?# Shell-style comment tags like those used in Perl look like this.# And the comment tag is only good for one line.$foo = "foo_value";         # Shell comments can also come after the code like this.?>

C-style comment tags are a little different. The slash star - star slash /* */ tags require the comment to be opened with a slash star and closed with a star slash.

<?/* Place your comment here and then close the comment */?>

The slash star - star slash comment tags require a bit more work but the work pays off. The comment can span accross several lines as long as the comment is correctly opened and closed.

<?/* My comment can be as long as I want,it can even use several lines.Whenever I get done commenting, I simply close the the comment. */?>

Additionally, the C-style comment can come before or after any code as long as the open and close tags are used properly.

<?/* Let's describe the code below,the code below is a variable definition. */$foo = "foo_value";                    /* The value of $foo is "foo_value" *//* But we have a second variable */   $widget = "5";     /* The value of $widget is "5" */?>

############################################################                                                      ####     Code Commenting Part Two - When To Comment       ####                                                      ## ##########################################################

Sorry, I know that that is rude.

Above please notice a block comment using a shell comment tag.

 

When a new section of code is started, you may want to use a bold statement like a block comment to introduce the next section. This may occur after defining all of your functions and before coding your output such as HTML.

 

The most common use of the block comment is at the top of the script to identify the script name, use, version, copyright info, and author info.

Example:

#############################################################                                                       ####  Code Commenting Tutorial Script In PHP.              ####  To be used by new programers to explain commenting   ####  Version 1.1                                          ####  Non Copyrighted Material                             ####  Witten By John Doe                                   ####                                                       ## ###########################################################

Comments before functions, especially complex functions, describing what the function does even if the function is pre-defined in PHP. This way if a bug pops up in the program, you can quickly identify the problem function.

<?// build_input_field() uses the arguments collected by the function call to create an HTML form input field.function build_input_field($type,$name,$value,$size,$maxlength) {$field = "<INPUT TYPE=\"$type\" NAME=\"$name\" VALUE=\"$value\" SIZE=\"$size\" MAXLENGTH=\"$maxlength\"><BR>\n";return $field;}?>

Another good place for a comment is near code that you have had or are having trouble writing.

Say you know what you want the code to do but are confussed about how to write it, Add a comment in the place in your code where you are having problems. The comment should describe what you wantto accomplish and what is causing problems.

This will help keep you focused on your goal. Many times the answer is obvious once we stop looking what went wrong and start looking at what went right. Too many people simply delete the problem code and start from scratch because of frustration.

The frustration comes from loosing focus of the logic you wanted to use. Comments remind you what the plan was.

Comments also make it easier for others to help you fix problems.

Example:

<?// Next I'd like to write a function that will automatically build a HTML form based on information// found in an SQL database table.// First I need a master function that will controll smaller functionsfunction foo_master() {    function foo_secondary_1() {        if (condition) {            $x = 1;            return $x;        }    function foo_secondary_2() {        if (condition) {            $x = 2;            return $x;        }    }}?>
Obviously, this code doesn't actually do anything.

 

Commenting can make a good script look great. Not only will comments help others to use your code but will make your code easier to write, fix, and modify.

 

Try to keep your comments on topic, jokes and personal comments just clutter the code. Sometimes the best comment is to let a piece os code speak for itself.

 

Remember, describe the code and what you want it to do and you'll find that your scripts will be easier to write.

 

Happy coding :P

vujsa

Share this post


Link to post
Share on other sites

Another very good article vujsa... I'm a programmer myself and working in the field of networked/distributed apps - I've long realized the importance of comments in the right place and what it can do to even your own code. Coz, if you leave your own code untouched for a while, when you get back to it next - I particularly find myself completely lost.. Comments always have helped me get started from the right point again... One of my professors in school used to harp on and on about the importance of comments - but I never realized how important they were in reality till I came down to sitting at a terminal 24/7 and writing code..

Another small tip I'd add to this is - for the more serious coders, try putting a comment wherever you end a function/loop/class with a curly brace "}".. For example

class SomeClass{      ..............                 function SomeFunction         {                  for (....)                  {                        ...............                   } // end for                  .............................          } // end of SomeFunction        ............} // end of SomeClass
The advantage of inserting such ending comments won't be apparent till you actually get around to doing it. For a long series of nested loops/classes, or loops inside a function - this makes your life immensely easier when you try to read your code later on. You KNOW for a fact exactly which brace terminates which class/function/loop

Anyways, good one. Glad to have you here among us :P

Share this post


Link to post
Share on other sites

microscopic^earthling,
Excelent tip. That may be the most important idea I've ever recived in a forum.

I can't begin to count the number of times I've left a closing bracket out and couldn't find it. Playing the open open close open open close open close close open close close game.

Sometimes you don't even get error or warning messages just nothing works.

Which leads me to a good follow up topic.
Indenting your code will help to clean your scripts up. Such indenting will provide as much information about your scripts as comments do.

Indentions help to identify command relationships and makes debugging you code easier.

Dependind on where you learn PHP an indent is either 4 or 5 spaces or a tab.
Tabs don't always show correctly in some script editors.
Standardization seems to be leaning towards 4 spaces and never tabs.

Here is an example of proper indentation:

<?$a = 1;$b = 2;$c = 3;if ($a == 1) {    function apple($x,$y,$z) {        $answer = $x +$y + $z;        return $answer;    } // End function apple()} // End IF Statementecho apple($a,$b,$c);  // Output Data?>

Happy coding :P
vujsa

Share this post


Link to post
Share on other sites

Very nice thread you started here vujsa! Another thing comments are good for is hiding code that you don't want a browser to display (perhaps because you don't need that code anymore or you're troubleshooting). This is called commenting out the code. I plan to do this to my webpages (whenever I get a new password PM'ed to me so that I can access cPanel for the first time, lol). Nice work, vujsa! :P

Share this post


Link to post
Share on other sites

Avery good tutorial. I have to second the rest of the posters here. You have quality posts and took the time to put it down for the rest of the community.Another +1 reputation point for you. :PNils

Share this post


Link to post
Share on other sites

Thanks you vujsa for the tips you gave us about the need to comment our php code. I agree that it has invaluable importance for any programmer but mainly for the beginners, because we need to develop good code habits early. Good, let's put it into practice right now! :rolleyes:

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.