PHP Code Formatter

CodeMorph

CodeToHtml

Coding Standards

PHP Coding Standard


You can read and download this PHP coding standard, coding guideline and reference from here for free at your own risk. All trademarks, registered trademarks, product names and company names or logos mentioned herein are the property of their respective owners.

PHP Coding Standard

Author: Victor Farazdagi

Date: 10/04/2002

PHP Coding Specifications

Disclaimer

I did my best to write this tutorial in an objective fashion. However, you have to understand that coding specifications presented here are written by myself for myself. They are neither universal standards nor were expected to be so. My aim was to help you develop your own coding style by introducing to existing one. Anything else is beyond the scope of this document.

Overview

This tutorial covers PHP coding style as the way of improving your programming skills. It explains benefits of well-formatted code and provides you with sample guidelines you may use in your own projects.

Except for PHP basics, there aren't any real prerequisites for understanding material provided.

Coding Standard: Why it's so important, after all?

To develop relatively complex system one has to work systematically. It is not so obvious but the coding style you employ plays an important role in achieving this goal.

The idea is very simple: consistent code is much easier to maintain.

So, here are several reasons why to use coding specifications:

Multi-developer environments require some standard laid down. Your peer programmers have to understand code you produce. Moreover, people new to PHP or your project would more easily figure out what it's all about.

Even if you develop alone it's advised to adhere to standards because it really pays off when you revise your code after couple of months.

Simplicity and clarity achieved by consistent coding saves you from common mistakes.

Code becomes really extensible and reusable. You don't have to worry if people working on your current application would understand some reusable feature recycled from last project.

It just looks professional!

General Guidelines

Always separate OO and Procedural code. Consider abandoning Procedural methodology at all. If you still want to use both OO and Procedural approaches don't mix them!

Don't use shell-like comments ('#') Shell-like comments may be declared as depreciated in near future, so use more conventional '//' or '/**/' comments instead.

Use full start-end tags i.e. (same reason with above).

File Templates: In order not to write same things every time you open new PHP file use templates.

Here, is sample PHP template file:

PHP Example: (!)

<?PHP

/*

* +------------------------------------------------------------------------------+

* Project Name

* +------------------------------------------------------------------------------+

* Copyright Notice(s)

* +------------------------------------------------------------------------------+

* Disclaimer Notice(s)

* ex: This code is freely given to you and given "AS IS", SO if it damages

* your computer, formats your HDs, or burns your house I am not the one to

* blame.

* Moreover, don't forget to include my copyright notices and name.

* +------------------------------------------------------------------------------+

* Author(s): Victor Farazdagi (Kuulest)

* +------------------------------------------------------------------------------+

*/

error_reporting(E_ALL); //For debugging purposes

/**

* Module comments (brief explanation about what this file is supposed to do)

*/

/*code goes here*/

/*

*tab-width=4

*indent=4

*width=90

*/

?>

Everything is quite straightforward, with the only possible exception for footer part. Tab-width, indent and width are supplied in order to make sure that your pretty code wouldn't get smashed by another coders's editor (consider him using 8 spaces as tab width, what he'd see is rather different from what you planned him to see).

Variable Naming

Actually, variable naming is a real art in itself. Separate article or even book may be written on this topic. What matters here is consistency. Whether you prefer camel-style variable naming (like intMyVar) or use "_" as word separators (like int_my_var) you have to keep it consistent throughout program.

Below, are guidelines for variable naming I use in my projects:

Generally, variable name must be in the following form (with the only exception of loop variables):

prefix + var_type + var_name

Let's look at it more closely:

Prefix

Prefix is used for clarification on the variable kind. It defines variable scope (whether it's global, temporary etc), purpose, parent package. Example prefixes are given below:

glb Global Variable

tmp Temporary Variable

frm Form Variable

Variable Type

Since PHP is not strong typed language (variable type is decided by PHP parser during the run time) it's a good idea to know type of variable you are working on. It prevents you from applying type-inappropriate operations on variables.

Possible abbreviations for type notation:

Scalar types:

int Integer

dbl Float-point, double

str String

bln Boolean

Compound types:

arr Array

obj Object

Special type:

res Resource

Variable Name

Here you have space for your creativity, but stay in frames.

From above only prefix part may be omitted.

Additional requirements:

All letters must be in lowercase.

Separate words and parts of variable name with underscores ("_").

Loop variables are denoted by $i, $j, $k and so on.

$str_query & $res_result are used for sql-query string and resource identifier respectively.

Ex: PHP Example: (!)

$arr_users

$glb_int_topic_id

$res_record_set

File Naming

All letters must be in lowercase (it matters on Unices).

Words are separated by "_".

No matter what use "php" extension.

Class extensions: inc.php

Ordinary php files: php

Keep your filenames under 32 chars.

SQL Query Formatting

SQL-keywords must be in uppercase

Ex: PHP Example: (!)

<?php

$str_query = "SELECT * FROM table_name WHERE name='Kuulest'";

?>

Operators

Add spaces before and after assigning, logical, arithmetic and comparison operators:

Ex: PHP Example: (!)

<?php

//assignment operators:

$a = 5;

$my_str .= "bla bla bla";

$i += 2;

//logical and comparison operators:

if (($name == 'Victor') or ($name == 'Andrei') ) {

echo 'Record found!';

}

//arithmetic operators:

$a = (10 * $b) / 20;

?>

Sometimes the following structure proves to be useful:

Ex: $int_very_long_name = 5;

$int_short = 5;

Control Structures

Let one space before and after control structure's brackets i.e. if () { .

Braces formatting is illustrated below. Because of space preservation I use unmatched braces style.

Use {} for indicating control structure body regardless of number of statements it contains.

Intendate by one tab (actually n spaces) code statements inside the control structure.

Put additional line between separate (not nested) control structures.

Never use alternative syntax for control structures (ex: if (cond):statements endif;)

Ex: PHP Example: (!)

<?php

// if; if..else; if..elseif;

if ($a == $b) {

/*code goes here*/

}

if ($a == $b) {

/*code goes here*/

}else {

/*code goes here*/

}

if ($a == $b) {

/*code goes here*/

}elseif ($a == $c) {

/*code goes here*/

}

// for; foreach; while;

// I let additional space after ';' in 'for' structure.

for ($i; $i < 10; $i++ ) {

/*code goes here*/

}

foreach ($arr as $k => $v ) {

/*code goes here*/

}

while ($i < 10) {

/*code goes here*/

}

// switch;

switch ($age) {

case 19:

echo 'You are in the army now!';

break;

case 100:

echo 'Incredible!!';

break;

default:

echo 'Nothing to say!';

}

?>

Functions

Let one space before and after function's brackets function i.e. my_func () {.

Functions names must be verbs. So do_sth() is better function name than the_sth().

Keep function names in lowercase.

Use "_" to separate words in function name.

Be descriptive but avoid too long functions' names.

Don't put extra space between function name and its brackets in function calls.

Ex: my_func();

Document functions as well as possible. If you like phpDocumentator's documentation generated from your comments

adhere to javadoc specifications.

PHP Example: (!)

<?php

/** Function: void login($str_user_name = 'nobody', $str_user_pass = 'nobody')

* ----------------------------------------------------------------

* Purpose: Member function handling user login process

* Arguments: $str_user_name - string, user name

* $str_user_pass - string, user password

* Returns/Assigns: Sets session variable $bln_logged to 1 if function

* call succeeds and 0 if otherwise.

*/

function login($str_user_name = 'nobody', $str_user_pass = 'nobody') {

/*code goes here*/

}

?>

Classes

Use camel-style variable naming. ex: SomeCamelClass

All of the above mentioned specifications apply to classes.

Ex: PHP Example: (!)

<?php

/**

* HTML Form elements generator for PHP4.

* Explanation: class purpose is to generate, store and transfer between pages

* form elements and their respective values.

* Supported HTML Form elements:

* text; password; radio; checkbox; image; file; hidden; button; submit; reset;

*/

class Form {

/*code goes here*/

}

?>

Summary

In this tutorial we tried to prepare PHP Coding Specifications. The way we did it is only one out of many.

So, you are advised to work on style standard most suitable for you and your projects.

Any constructive comments are welcome and would be greatly appreciated.

You can reach me at farazdagi at linuxmail dot org.

  Still reformat PHP code by hand?  Use SourceFormatX PHP Code Formatter to format all PHP code files for you!