Coding - Coding Style
(Page 4 of 10 )
Whether for good or for bad, the days of spaghetti code (a slang expression used to describe any badly designed or poorly structured program that is hard to unravel or understand as a bowl of spaghetti) are gone, so how you code is just as important as what you code. Now I don't want to start a flame war over which set of standards are better then others--for example tabs or spaces. It is irrelevant what particular style or system you use when writing your code as long as you consistently follow it throughout the entire script. An example of one is PEAR's coding standard..
Indention
One area in particular I want to be sure to touch on is indention. Indention is used to visually group logic blocks for easier reading and understanding and also helps for matching parenthesis. Use 2, 3, or 4 spaces, tabs or whatever you prefer to indent--just stick with it.
<?php if (isset($_SERVER["REMOTE_ADDR"])) { $octet = substr($_SERVER["REMOTE_ADDR"], 0, strpos($_SERVER["REMOTE_ADDR"], ".")); switch ($octet) { case 127: $network_class = "Reserved Loopback"; break; case ($octet <= 126): $network_class = "Class A"; break; case ($octet <= 191): $network_class = "Class B"; break; case ($octet <= 223): $network_class = "Class C"; break; case ($octet <= 239): $network_class = "Class D"; break; case ($octet <= 255): $network_class = "Class E"; break; default: $network_class = "Unknown Class"; break; } } else { $network_class = "Unknown Class"; } echo "Your IP address is: $network_class"; ?> |
Variable Naming
In PHP variables are required to start with a letter or underscore, followed by any number of letters, numbers or underscores. It should also be noted that PHP variables are case-sensitive, so $var and $Var are 2 separate variables. Also, make sure you also use variable names that provide information for what the variable will be used for or where it came from. There is no real limit on how long a variable name can be; the only limits are how much typing you want to do.
<?php $x // no idea what it is for. $num // better – at least you now know it is a number, // but a number for what? $cc_num // better yet – at least now we know it is a credit // card number being held in the variable // (or is it a cheddar cheese stock number?) $cred_card_num //best variable name $chedChezStockNum //best variable name ?> |
Next: Error Reporting >>
More Programming Basics Articles
More By lig