PHPBuilder - Comprehensible PHP Code Page 2



RSS Twitter
Articles Code Documentation

Comprehensible PHP Code - Page 2

by: PHP Builder Staff
|
October 3, 2001

Block Comments
Comments form an important part in documentation. You can start the program with a brief description of the entire program on top of the page. Here is how you can do this:

<?php

/***********************************************************
* Class to populate the <select> form field from mysql table
* This class enables you to populate a select form field with
* option lists from any database.
* Made By Sujith Nair [sujith_77@hotmail.com]
* On September 14, 2001
************************************************************/

class populate_sel {


var 
$hname="<hostname>";
var 
$uname="<username>";
var 
$pname="<password>";
var 
$dbname="<database name>";
var 
$tname;
var 
$fname;
var 
$sel;

// And the code follows
?>
The first few lines gives a brief description of the class. This is how I prefer to display a block of description.
Line comments
Line comments can be used to explain any particular action in the code. This is demonstrated below.

<?php

function populate_sel($t_name,$f_name,$sel=""// Constructor to initialize relevant values.
{
    
$this->tname=$t_name;
    
$this->fname=$f_name;
    
$this->sel=$sel;
}
// And the code follows
?>
I prefer to place the Line Comment on the same line with the particular action, rather than placing it above or below the action. The Following is what I don't prefer:

<?php

// Constructor to initialize relevant values.
function populate_sel($t_name,$f_name,$sel="")
{
    
$this->tname=$t_name;
    
$this->fname=$f_name;
    
$this->sel=$sel;
}
// And the code follows
?>
Indenting
The code should be properly indented so that the control structures are visible and can be properly understood. The PEAR RFC standard recommends four spaces, not tabs of any size, in your code. But you can use spaces for the same. Here is an example of indenting code.

<?php

function foo()
{

while(
c){

if(
a==b){
    if(
b==c){
        
// code follows
            
}
        else{
            
// code follows
                
}
        }
        else{
            
// code follows
            
}

    }

    
// code follows

}
// And the code follows
?>
I prefer opening parenthesis to follow the conditions in control structures, but the opening parenthesis should start with the new line in case of functions or classes or class members. Also the IF and ELSE statements should be well covered by braces.

« Previous Page
1
|
2
|
3
Next Page »

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:

Comment:



Comment:

(Maximum characters: 1200). You have characters left.