====== PHP Coding Standards ======
===== Naming Conventions =====
==== Variables and Function Agrument names ====
* Variables and Function Agrument names should be named using the "studly caps" style (also referred to as "bumpy case" or "camel caps" or "java style"). The initial letter of the name is lowercase, and each letter that starts a new "word" is capitalized.
Example:
function doTest($sumCount, $value){
$sum = 0;
for ($i = 0; $i < $sumCount; $i++) {
$sum += $value;
}
return $sum;
}
==== Constants ====
* Constants should always be all-uppercase, with underscores to separate words.
* When using the built-in PHP constants true, false and null always type them in **lower case**
Example:
define('A_GLOBAL_CONSTANT', 'Hello world!');
==== Hash Array Keys ====
* Array element names follow the same rules as a variable.
* Always quote non-numerical key when access the element. Also consider creating a constant for the key name
Example:
echo $valuesArray[2]; // Bad
echo $valuesArray[THE_SPECIAL_KEY]; // Good
echo $valuesArray[foo]; // Very Bad
echo $valuesArray['foo']; // Bad
echo $valuesArray[THE_FOO_KEY]; // Good
==== Functions and Method Names ====
Use the same convention as [[#Variables and Function Agrument names|variable names]]
Examples:
getData(), serialize(), isReady()
==== Class Names ====
* Use upper case letters as word separators, lower case for the rest of a word
* First character in a name is upper case
* No underbars ('_')
* Classes can be prepended with lower case prefix which describes the library or the framework that the class belongs.
Example:
ClassName, AnotherClass, opClassInOurProject
==== Class Attribute Names ====
* Use the same convention as [[#Variables and Function Agrument names|variables]]
* Public class members are declared as public unless you need to make getter/setter. When you need to define getter/setter - make it protected/private and use PHP 5 member overloading to make getters/setters. When possible use [[nscl:c-nsobject|nsObject]] to define getters setters.
Example:
private $_privateData; // wrong - do not perpend private or protected methods with underscore (_)
public $action; // Public member variable. Don't bother using public variables. When you need to define getter and setter - make it protected and use member overloading.
protected $action; // Private member variable.
==== No All Upper Case Abbreviations ====
* When confronted with a situation where you could use an all upper case abbreviation instead use an initial upper case letter followed by all lower case letters.
* Do use: getHtmlStatistic.
* Do not use: getHTMLStatistic.
* Do use: getId
* Do not use: getID
* Justification
People seem to have very different intuitions when making names containing abbreviations. It's best to settle on one strategy so the names are absolutely predictable.
Take for example networkABCKey. Notice how the C from ABC and K from key are confused. Some people don't mind this and others just hate it so you'll find different policies in different code so you never know what to call something.
Example:
class FluidOz // NOT FluidOZ
class GetHtmlStatistic // NOT GetHTMLStatistic
===== Control Structures =====
These include if, for, while, switch, etc. Here is an example if statement, since it is the most complicated form:
* Example if() structure:
if ((condition1) || (condition2)){
action1;
} elseif ((condition3) && (condition4)){
action2;
} else {
defaultaction;
}
* Example for() structure:
for ($i = 0; $i < 100; $i++) {
...
}
* Example foreach() structure:
foreach ($array as $value) {
}
foreach ($array as $key => $value) {
}
foreach ($array as $key=>$value) { // only here you can skip space around =>
}
* Example switch() structure:
switch ($value) {
case 1:
echo 1;
break;
case 'hello':
echo 'hello';
break;
default:
echo 'default';
}
* Example while() structure:
while ($i < 100) {
...
$i++;
}
* Example do while() structure:
do {
...
$i++;
} while ($i < 100);
* Control statements shall not have one space between the control keyword and opening parenthesis.
* Do not use the alternative syntax for the control structures
===== Classes =====
Use the following class declaration style:
class SomeClass extends ParentClass {
...
}
===== Method and Field Modifiers =====
The method of field modifiers are one or more of:
public protected private abstract static final
Although the order of the modifiers is not significant to the compiler for consistency reasons use the order above, eg:
public static function a()
protected final function b()
public abstract static function a()
===== Functions =====
==== Function Declarations ====
Functions should be placed inside classes when possible. The syntax of function declarations are showed in the snipped below.
function myFunction($paramA = 1, $paramB = 2){
return 42;
}
* Functions should be short and do one thing.
* You should let the parameter line go over several lines with grouping of the similar parameters, if it gets long.
==== Function Calls ====
Functions shall be called with no spaces between the function name, the opening parenthesis, and the first parameter; spaces between commas and each parameter, and no space between the last parameter, the closing parenthesis, and the semicolon. Here's an example:
$var = foo($bar, $baz, $quux);
As displayed above, there should be one space on either side of an equals sign used to assign the return value of a function to a variable.
In the case of a block of related assignments, do not align on the equal sign.
$short = foo($bar); // WRONG !
$long_variable = foo($baz);
===== Operators =====
* Add spaces before and after assigning, logical, arithmetic and comparison operators. Unary operator do not require spaces:
// 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;
// unary operators:
$i++;
* Do not rely on everyone knowing all operators precedence. Other people might not be as brilliant as you. Use parenthesis:
/* what's the result? who knows? */
$bool = ($i < 7 && $j > 8 || $k == 4);
/* now you can be certain what I'm doing here. */
$bool = (($i < 7) && (($j > 8) || ($k == 4)))
===== Parenthesis, brackets and comma =====
* Do not put a space after a start parenthesis or before an end parenthesis.
* One space is placed after every comma.
* Square brackets [] should not have space before or after the start bracket and before the end bracket.
* Use more parenthesis than necessary if you're not certain in which sequence the expression is executed.
===== Strings =====
* Use ' instead of "
* Do not use variables expansion
* Use: echo 'hello ' . $name;
* Do not use: echo "hello $name"
===== Indenting =====
* Indenting is 2 characters
* Spaces are used for indenting.
* real tab characters should not be used
===== Line Formatting =====
* Try to limit the length of the line to 75 - 85 characters per line.
* When breaking line because it is too long indent the next line so it matches. Example:
$result = createUser($username, $password, $password2, $firstName, $lastName,
$email, $phone);
* This is how to break strings. Always close the string on the same line that it was opened, and align the quotes.
$longText = 'This is a very long sentence that ' .
'needs splitting';
* Use UNIX-style line endings, unless you need to work with other operating systems data. Lines end with "\n", not with "\r\n"!
===== Statements per line =====
* Put only one statement per line
// Correct
$a = 1;
$b = 1;
// Incorrect
$a = 1; $b = 1;
===== PHP Code Tags =====
* Always use **** to delimit PHP code, not the ** ?>** shorthand.
* Do not put ?> at the end of file when it's not a template. Not closing php tag is allowed and prevents white space at end. Some browsers add a new line at the end of file.
===== Comments =====
* Try to comment all files, classes, functions, methods and variables using PHPDoc comments. For details about PHPDoc refer to http://www.stack.nl/~dimitri/doxygen/docblocks.html
* Use /*! ... */ syntax instead /** * * */
/*!
A comment block
it doesn't contain vertical asterisks
*/
* Use one space after the comment start
Incorrect:
//some comment
Correct:
// some comment
===== HTML =====
* Do not mix HTML with PHP. Do not put HTML code inside PHP files. Use template files.
* Template files can also be PHP files!
* If using template file is not convinient store the HTML in a separate contants only file, or in the database.
* When writing HTML make use of CSS. Do not use , , etc. tags
===== Including files =====
* Use require_once() to include files or reqire() for templates.
* In each file include only the files you need. But do include all the files that you need.
===== Naming files =====
* Use only lower case characters. Use - to separate words. This is for both file names and directory names.
* For user viewable files use .php extension. Do not use .phtml
* For included files use .inc.php extension, not .inc!
* Group files relating to managing a single entity into a separate directory
===== SQL Queries =====
* Query should be writen using single quotes (').
* Queries longer then one line must be broken by the logical breaks between SQL keywords.
* All parameters given to the query must be escaped, usually with mysql_real_escape_string() or nsDatabase::escape().
* SQL-keywords must be in uppercase
Example:
$db->query('SELECT * FROM users WHERE id = '.intval($userId).' and status != "'.$db->escape(US_ACTIVE).'"');
===== Project Structure =====
FIXME
* Put all include files in include directory. Create subdirectories under the include directory for each package. For each package put the related files in their own subdirectories based on their functions.
Example:
/include/
/include/miphpf/
/include/miphpf/const/
/include/miphpf/model/
/include/miphpf/view/
/include/miphpf/util/
* If you have an admin area create admin directory and create directories beneath it for each admin finction.
Example:
/admin/
/admin/employees/
/admin/managers/
/admin/config/
/admin/lists/
* If you have an user area create users directory and create directories beneath it for each user finction.
* Use header and footer files. Name them header.html and footer.html, or header.php and footer.php, depending if they contain PHP code. It is allowed to mix PHP with HTML in the header and footer files if needed.
===== Epilogue =====
Please follow the standards above. Consider these reasons:
* programmers can go into any code and figure out what's going on
* new people can get up to speed quickly
* people new to PHP are spared the need to develop a personal style and defend it to the death
* people make fewer mistakes in consistent environments
If you find that you are wondering how to write a certain piece of code, and the correct style is not described here, or is not clear, please contact the author/maintainer so that the needed amendment can be made.
And the final point is that the standard is not written in stone. If in a certain situation it makes all the sense in the world not to follow the standard, then do what is best for the project.