Coding guidelines

PHP coding talk.

Moderator: Moderators

Coding guidelines

Postby PostBot on Wed Mar 10, 2004 9:26 am

Most of this document is borrowed from phpBB Group coding guidelines because their guidelines are almost perfect and there is no need to reinvent it.

This is recommendation on how to correctly write PHP code. If you follow these guidelines your code will be easy to read and it will be fast.


  1. Editor Settings

    Tabs vs Spaces: In order to make this as simple as possible, we will be using tabs, not spaces. Feel free to set how many spaces your editor uses when it displays tabs, but make sure that when you save the file, it's saving tabs and not spaces. This way, we can each have the code be displayed the way we like it, without breaking the layout of the actual files.

    Linefeeds: Ensure that your editor is saving files in the UNIX format. This means lines are terminated with a newline, not with a CR/LF combo as they are on Win32, or whatever the Mac uses. Any decent Win32 editor should be able to do this, but it might not always be the default. Know your editor. If you want advice on Windows text editors, just ask one of the developers. Some of them do their editing on Win32.
  2. Naming Conventions

    We will not be using any form of hungarian notation in our naming conventions. Many of us believe that hungarian naming is one of the primary code obfuscation techniques currently in use.

    Variable Names: Variable names should be in all lowercase, with words separated by an underscore, example:
    $current_user is right, but $currentuser and $currentUser are not.

    Names should be descriptive, but concise. We don't want huge sentences as our variable names, but typing an extra couple of characters is always better than wondering what exactly a certain variable is for.

    Loop Indices: The only situation where a one-character variable name is allowed is when it's the index for some looping construct. In this case, the index of the outer loop should always be $i. If there's a loop inside that loop, its index should be $j, followed by $k, and so on. If the loop is being indexed by some already-existing variable with a meaningful name, this guideline does not apply, example:
    Code: Select all
    for ($i = 0; $i < $outer_size; $i++)
    {
       for ($j = 0; $j < $inner_size; $j++)
       {
          foo($i, $j);
       }
    }


    Function Names: Functions should also be named descriptively. We're not programming in C here, we don't want to write functions called things like "stristr()". Again, all lower-case names with words separated by a single underscore character. Function names should preferably have a verb in them somewhere. Good function names are print_login_status(), get_user_data(), etc.

    Function Arguments: Arguments are subject to the same guidelines as variable names. We don't want a bunch of functions like: do_stuff($a, $b, $c). In most cases, we'd like to be able to tell how to use a function by just looking at its declaration.

    Summary: The basic philosophy here is to not hurt code clarity for the sake of laziness. This has to be balanced by a little bit of common sense, though; print_login_status_for_a_given_user() goes too far, for example -- that function would be better named print_user_login_status() , or just print_login_status().
  3. Code Layout

    Always include the braces: This is another case of being too lazy to type 2 extra characters causing problems with code clarity. Even if the body of some construct is only one line long, do not drop the braces. Just don't, examples:

    Code: Select all
    /* These are all wrong. */

    if (condition) do_stuff();

    if (condition)
       do_stuff();

    while (condition)
       do_stuff();

    for ($i = 0; $i < size; $i++)
       do_stuff($i);

    Code: Select all
    /* These are all right. */

    if (condition)
    {
       do_stuff();
    }

    while (condition)
    {
       do_stuff();
    }

    for ($i = 0; $i < size; $i++)
    {
       do_stuff();
    }


    Where to put the braces: This one is a bit of a holy war, but we're going to use a style that can be summed up in one sentence: Braces always go on their own line. The closing brace should also always be at the same column as the corresponding opening brace, examples:

    Code: Select all
    if (condition)
    {
       while (condition2)
       {
          ...
       }
    }
    else
    {
       ...
    }

    for ($i = 0; $i < $size; $i++)
    {
       ...
    }

    while (condition)
    {
       ...
    }

    function do_stuff()
    {
       ...
    }

  4. General Guidelines

    Quoting strings: There are two different ways to quote strings in PHP - either with single quotes or with double quotes. The main difference is that the parser does variable interpolation in double-quoted strings, but not in single quoted strings. Because of this, you should always use single quotes unless you specifically need variable interpolation to be done on that string. This way, we can save the parser the trouble of parsing a bunch of strings where no interpolation needs to be done and your code will work much faster.

    Also, if you are using a string variable as part of a function call, you do not need to enclose that variable in quotes. Again, this will just make unnecessary work for the parser. Note, however, that nearly all of the escape sequences that exist for double-quoted strings will not work with single-quoted strings. Be careful, and feel free to break this guideline if it's making your code harder to read, examples:

    Code: Select all
    /* wrong */

    $str = "This is a really long string with no variables for the parser to find.";

    do_stuff("$str");

    Code: Select all
    /* right */

    $str = 'This is a really long string with no variables for the parser to find.';

    do_stuff($str);


    Associative array keys: In PHP, it's legal to use a literal string as a key to an associative array without quoting that string. We don't want to do this -- the string should always be quoted to avoid confusion. Note that this is only when we're using a literal, not when we're using a variable. Using double quotes in array keys is also not welcomed becuase it parses slower than single quotes. Examples:

    Code: Select all
    /* wrong */

    $foo = $assoc_array[blah];
    $foo = $assoc_array["blah"];

    Code: Select all
    /* right */

    $foo = $assoc_array['blah'];


    Comments: Each function should be preceded by a comment that tells a programmer everything they need to know to use that function. The meaning of every parameter, the expected input, and the output are required as a minimal comment. The function's behaviour in error conditions (and what those error conditions are) should also be present. Nobody should have to look at the actual source of a function in order to be able to call it with confidence in their own code.

    In addition, commenting any tricky, obscure, or otherwise not-immediately-obvious code is clearly something we should be doing. Especially important to document are any assumptions your code makes, or preconditions for its proper operation. Any one of the developers should be able to look at any part of the application and figure out what's going on in a reasonable amount of time.

    Magic numbers: Don't use them. Use named constants for any literal value other than obvious special cases. Basically, it's OK to check if an array has 0 elements by using the literal 0. It's not OK to assign some special meaning to a number and then use it everywhere as a literal. This hurts readability AND maintainability. Included in this guideline is that we should be using the constants TRUE and FALSE in place of the literals 1 and 0 -- even though they have the same values, it's more obvious what the actual logic is when you use the named constants.

    Shortcut operators: The only shortcut operators that cause readability problems are the shortcut increment ($i++) and decrement ($j--) operators. These operators should not be used as part of an expression. They can, however, be used on their own line. Using them in expressions is just not worth the headaches when debugging, examples:
    Code: Select all
    /* wrong */

    $array[++$i] = $j;
    $array[$i++] = $k;

    Code: Select all
    /* right */

    $i++;
    $array[$i] = $j;

    $array[$i] = $k;
    $i++;


    Don't use uninitialized variables. When you are using uninitialized variables it causes potencial security problem because visitor can easily pass extra parameters to your script via GET/POST and if register_globals is enabled it will create extra variables. And if you don't know if variable was initialized use isset() or empty() to check it.

    Don't rely on register_globals. Same reason as above - potencial security hole. To use GET/POST variables use $_GET['variable_name'] or $_POST['variable_name'], go use server variables use $_SERVER['variable_name'].

    Use proper php tags: PHP code should start with <?php, not <?, not <?PHP. This way it will work with all configurations and everyone would be able to easily read it.
Do NOT pm me, I don't visit this forum anymore, don't own it, don't provide any support and don't moderate.
User avatar
PostBot
Moderator
Moderator
 
Posts: 10659
Joined: Sat Aug 02, 2003 3:52 pm
Location: Mars

Re: Coding guidelines

Postby thefilmwall on Sat Apr 11, 2009 10:20 pm

When I read this book then I think that I can understand better than other programing language because
coding of PHP is very easy and any person can understand easy way. Looping,inheritance,array,function....etc is give very good.
Functions need not be defined before they are referenced, except when a function is conditionally defined as shown in the below.
When a function is defined in a conditional manner such as the examples shown. Its definition must be processed prior to being called.
Conditional functions
<?php
$makefoo = true;
/* We can't call foo() from here
since it doesn't exist yet,
but we can call bar() */
bar();
if ($makefoo) {
function foo()
{
echo "I don't exist until program execution reaches me.\n";
}
}
/* Now we can safely call foo()
since $makefoo evaluated to true */
The Film Wall is a place where you can watch [url="http://www.thefilmwall.com"]online free movies[/url]anytime.
thefilmwall
Registered User
Registered User
 
Posts: 1
Joined: Thu Apr 09, 2009 11:45 pm
Location: USA

Re: Coding guidelines

Postby arlyn9391 on Sat May 02, 2009 6:45 am

PostBot wrote:Most of this document is borrowed from phpBB Group coding guidelines because their guidelines are almost perfect and there is no need to reinvent it.

This is recommendation on how to correctly write PHP code. If you follow these guidelines your code will be easy to read and it will be fast.


  1. Editor Settings

    Tabs vs Spaces: In order to make this as simple as possible, we will be using tabs, not spaces. Feel free to set how many spaces your editor uses when it displays tabs, but make sure that when you save the file, it's saving tabs and not spaces. This way, we can each have the code be displayed the way we like it, without breaking the layout of the actual files.

    Linefeeds: Ensure that your editor is saving files in the UNIX format. This means lines are terminated with a newline, not with a CR/LF combo as they are on Win32, or whatever the Mac uses. Any decent Win32 editor should be able to do this, but it might not always be the default. Know your editor. If you want advice on Windows text editors, just ask one of the developers. Some of them do their editing on Win32.
  2. Naming Conventions

    We will not be using any form of hungarian notation in our naming conventions. Many of us believe that hungarian naming is one of the primary code obfuscation techniques currently in use.

    Variable Names: Variable names should be in all lowercase, with words separated by an underscore, example:
    $current_user is right, but $currentuser and $currentUser are not.

    Names should be descriptive, but concise. We don't want huge sentences as our variable names, but typing an extra couple of characters is always better than wondering what exactly a certain variable is for.

    Loop Indices: The only situation where a one-character variable name is allowed is when it's the index for some looping construct. In this case, the index of the outer loop should always be $i. If there's a loop inside that loop, its index should be $j, followed by $k, and so on. If the loop is being indexed by some already-existing variable with a meaningful name, this guideline does not apply, example:
    Code: Select all
    for ($i = 0; $i < $outer_size; $i++)
    {
       for ($j = 0; $j < $inner_size; $j++)
       {
          foo($i, $j);
       }
    }


    Function Names: Functions should also be named descriptively. We're not programming in C here, we don't want to write functions called things like "stristr()". Again, all lower-case names with words separated by a single underscore character. Function names should preferably have a verb in them somewhere. Good function names are print_login_status(), get_user_data(), etc.

    Function Arguments: Arguments are subject to the same guidelines as variable names. We don't want a bunch of functions like: do_stuff($a, $b, $c). In most cases, we'd like to be able to tell how to use a function by just looking at its declaration.

    Summary: The basic philosophy here is to not hurt code clarity for the sake of laziness. This has to be balanced by a little bit of common sense, though; print_login_status_for_a_given_user() goes too far, for example -- that function would be better named print_user_login_status() , or just print_login_status().
  3. Code Layout

    Always include the braces: This is another case of being too lazy to type 2 extra characters causing problems with code clarity. Even if the body of some construct is only one line long, do not drop the braces. Just don't, examples:

    Code: Select all
    /* These are all wrong. */

    if (condition) do_stuff();

    if (condition)
       do_stuff();

    while (condition)
       do_stuff();

    for ($i = 0; $i < size; $i++)
       do_stuff($i);

    Code: Select all
    /* These are all right. */

    if (condition)
    {
       do_stuff();
    }

    while (condition)
    {
       do_stuff();
    }

    for ($i = 0; $i < size; $i++)
    {
       do_stuff();
    }


    Where to put the braces: This one is a bit of a holy war, but we're going to use a style that can be summed up in one sentence: Braces always go on their own line. The closing brace should also always be at the same column as the corresponding opening brace, examples:

    Code: Select all
    if (condition)
    {
       while (condition2)
       {
          ...
       }
    }
    else
    {
       ...
    }

    for ($i = 0; $i < $size; $i++)
    {
       ...
    }

    while (condition)
    {
       ...
    }

    function do_stuff()
    {
       ...
    }

  4. General Guidelines

    Quoting strings: There are two different ways to quote strings in PHP - either with single quotes or with double quotes. The main difference is that the parser does variable interpolation in double-quoted strings, but not in single quoted strings. Because of this, you should always use single quotes unless you specifically need variable interpolation to be done on that string. This way, we can save the parser the trouble of parsing a bunch of strings where no interpolation needs to be done and your code will work much faster.

    Also, if you are using a string variable as part of a function call, you do not need to enclose that variable in quotes. Again, this will just make unnecessary work for the parser. Note, however, that nearly all of the escape sequences that exist for double-quoted strings will not work with single-quoted strings. Be careful, and feel free to break this guideline if it's making your code harder to read, examples:

    Code: Select all
    /* wrong */

    $str = "This is a really long string with no variables for the parser to find.";

    do_stuff("$str");

    Code: Select all
    /* right */

    $str = 'This is a really long string with no variables for the parser to find.';

    do_stuff($str);


    Associative array keys: In PHP, it's legal to use a literal string as a key to an associative array without quoting that string. We don't want to do this -- the string should always be quoted to avoid confusion. Note that this is only when we're using a literal, not when we're using a variable. Using double quotes in array keys is also not welcomed becuase it parses slower than single quotes. Examples:

    Code: Select all
    /* wrong */

    $foo = $assoc_array[blah];
    $foo = $assoc_array["blah"];

    Code: Select all
    /* right */

    $foo = $assoc_array['blah'];


    Comments: Each function should be preceded by a comment that tells a programmer everything they need to know to use that function. The meaning of every parameter, the expected input, and the output are required as a minimal comment. The function's behaviour in error conditions (and what those error conditions are) should also be present. Nobody should have to look at the actual source of a function in order to be able to call it with confidence in their own code.

    In addition, commenting any tricky, obscure, or otherwise not-immediately-obvious code is clearly something we should be doing. Especially important to document are any assumptions your code makes, or preconditions for its proper operation. Any one of the developers should be able to look at any part of the application and figure out what's going on in a reasonable amount of time.

    Magic numbers: Don't use them. Use named constants for any literal value other than obvious special cases. Basically, it's OK to check if an array has 0 elements by using the literal 0. It's not OK to assign some special meaning to a number and then use it everywhere as a literal. This hurts readability AND maintainability. Included in this guideline is that we should be using the constants TRUE and FALSE in place of the literals 1 and 0 -- even though they have the same values, it's more obvious what the actual logic is when you use the named constants.

    Shortcut operators: The only shortcut operators that cause readability problems are the shortcut increment ($i++) and decrement ($j--) operators. These operators should not be used as part of an expression. They can, however, be used on their own line. Using them in expressions is just not worth the headaches when debugging, examples:
    Code: Select all
    /* wrong */

    $array[++$i] = $j;
    $array[$i++] = $k;

    Code: Select all
    /* right */

    $i++;
    $array[$i] = $j;

    $array[$i] = $k;
    $i++;


    Don't use uninitialized variables. When you are using uninitialized variables it causes potencial security problem because visitor can easily pass extra parameters to your script via GET/POST and if register_globals is enabled it will create extra variables. And if you don't know if variable was initialized use isset() or empty() to check it.

    Don't rely on register_globals. Same reason as above - potencial security hole. To use GET/POST variables use $_GET['variable_name'] or $_POST['variable_name'], go use server variables use $_SERVER['variable_name'].

    Use proper php tags: PHP code should start with <?php, not <?, not <?PHP. This way it will work with all configurations and everyone would be able to easily read it.







Thank you for the wonderful recommendation on how to correctly write PHP code. I will follow these guidelines so that my code will be easy to read and it will be fast. Thank you. :D


_________________
Scotsman Ice Machine
arlyn9391
Registered User
Registered User
 
Posts: 1
Joined: Sat May 02, 2009 5:24 am


Return to PHP Programming

Who is online

Users browsing this forum: Google [Bot] and 3 guests