Wednesday, March 4, 2020

How and Why to Comment in Your PHP Code

How and Why to Comment in Your PHP Code A comment in PHP code is a line that is not read as part of the program. Its only purpose is to be read by someone who is editing the code. So why use comments? To let others know what youre doing. If you are working with a group of people or plan on anyone else ever using your script, the comments tell the other programmers what you were doing in each step. This makes it much easier for them to work with and to edit your code if needed.To remind yourself what you did. Although you may just be writing a quick script for yourself and dont see the need for comments, go ahead and add them in anyway. Most programmers have experienced coming back to edit their own work a year or two later and having to figure out what they did. Comments can remind you of your thoughts when you wrote the code. There are several ways to add a comment in PHP code. The first is by using // to comment out a line. This one-line comment style only comments to the end of the line or the current code block, whichever comes first. Here is an example: ?php echo hello; //this is a comment echo there; ? If you have a single line comment, another option is to use a # sign. Here is an example of this method: ?php echo hello; #this is a comment echo there; ? If you have a longer, multi-line comment, the best way to comment is with /* and  */ before and after a lengthy comment. You can contain several lines of commenting inside a block. Here is an example: ?php echo hello; /* Using this method you can create a larger block of text and it will all be commented out */ echo there; ? Dont Mix Comments Although you can nest comments within comments in PHP, do so carefully. Not all of them nest equally well. PHP supports C, C and Unix shell-style comments. C style comments end at the first */ they encounter, so dont nest C style comments.   If you are working with PHP and HTML, be aware that HTML comments mean nothing to the PHP parser. They wont work as intended and are likely to execute some function. So, stay away from:   !Comment

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.