Tips for Coding Cleaner PHP

PHP is lovely, though if you ever work with other people having good code is important. Here are some tips to improve your code.

Comment & Document
It’s really important that people understand why you are doing certain things in certain ways. Adding a quick comment above sections of code should be adequate, but documenting classes and functions is fantastic.

Give Variables, Functions and Classes Meaningful names
Nothing is worse than trying to figure out what a function does. Give everything a name that if someone else looked at it, they could figure out what it does.

function fetch_user_info();

Never Delete – Comment out
This one is a little hard to grasp, but imagine you just fixed a bug (say 50 lines of code to fix it) and something else has broken. It makes sense to be able to go back and see the old code without modification of the new code. Also, doing this helps people see where an old bug was for future reference.

Use Braces
Braces are those neat } and { things. If you don’t use them on various functions it’s a pain to figure out where a loop starts and finishes.
This is especially important when programming on a large scale because no one likes debugging fugly code.
Here is an example of good and bad code:

/* Examples of bad code */
if ( $product === 'Car' ) use_seat_belt();
while ( $product === 'Car' )

/* Examples of good code*/
if ( $product === 'Car' ){ use_seat_belt(); }

while ( $product !== 'Car' ){