Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 9 of 9
  1. #1
    Super Moderator JohnDubya's Avatar
    Join Date
    Nov 2006
    Location
    Missouri
    Posts
    634
    Thanks
    12
    Thanked 18 Times in 18 Posts

    PHP Best Practices (no replies here please!)

    Hello there, all you mad PHP coders out there. I am starting this thread in the hopes that it will turn out really helpful to those wishing to make their experience with coding in PHP more efficient and practical. As we all know, there are a hundred different ways to do the same thing, but some solutions are better than others. That's what this thread is for. My wish is that this would turn into a sticky, but we'll see how it goes.

    This thread is specifically for me to post finished "Best Practices" (BP) discussions. I would ask that all discussion of "Best Practices" be kept to the PHP Best Practices - Discussion thread. In other words, please don't post ANYTHING to this thread, but instead, use the discussion thread. I can't enforce this, of course, but I would ask it in the interest of organization.

    For each BP post, the title at the top of the post is the subject of the BP. I will number the responses/websites from people and link the number to their post/website. I also believe in giving credit where credit is due, so credit will be given at the bottom of each response/website.

    If there is something on this thread that is inconsistent, incorrect, or not the best practice, please post it on the discussion thread, not this one.

    I am going to keep this thread up to date by posting new BP and editing already posted BP.

    I hope you find this thread very helpful on your continued learning journey through PHP. Good luck!
    Last edited by JohnDubya; 02-23-2007 at 07:49 PM.

  • #2
    Super Moderator JohnDubya's Avatar
    Join Date
    Nov 2006
    Location
    Missouri
    Posts
    634
    Thanks
    12
    Thanked 18 Times in 18 Posts

    Always use <?php instead of <?

    [1]
    A pretty basic one. Always use:

    PHP Code:
    <?php
    Not:

    PHP Code:
    <?
    Because if you are working for a client or your server doesn't have php_short_tags on, your code will be broken.

    [thanks to Webmonkey]


    [2]
    Although <? and <% are available for use to enter PHP mode, their use is not encouraged for several reasons:

    • They are not enabled by default
    • They may not be available on other machines
    • <? is not XML-compliant
    • Always, always, always use <?php. Always - with no exceptions!


    [from http://hudzilla.org/phpwiki/index.ph...ng_code_blocks]
    Last edited by JohnDubya; 02-23-2007 at 05:52 PM.

  • #3
    Super Moderator JohnDubya's Avatar
    Join Date
    Nov 2006
    Location
    Missouri
    Posts
    634
    Thanks
    12
    Thanked 18 Times in 18 Posts

    Use switch() over if() whenever possible

    [1]
    Use switch() in preference to if() anytime you can. To be able to refactor a bunch of ifs as a switch (a) they must all test the same subject and (b) they must test for single values (==) and not ranges (<, >, <=, >=, != [although one of these can often be covered by the default case])

    If the goal of the chain of ifs is to assign a single variable different values depending on the conditions *and there are no side effects of testing the conditions* it should be expressed as ternary instead of as if or else. Ternary for assignment is idiomatic in many languages, inc. PHP.

    [thanks to ralph l mayo]


    [2]
    To get around single values or equality used in switch(), you can also use:

    PHP Code:
    <?php
    switch(true){
      case 
    $cond && $cond2 :/*blah*/;
    }
    ?>
    [thanks to firepages]
    Last edited by JohnDubya; 02-23-2007 at 05:48 PM.

  • #4
    Super Moderator JohnDubya's Avatar
    Join Date
    Nov 2006
    Location
    Missouri
    Posts
    634
    Thanks
    12
    Thanked 18 Times in 18 Posts

    When to use mysql_fetch_assoc() or mysql_fetch_array()

    [1]
    Prefer to fetch an array when it would not compromise readability (when 1. you're only selecting 1 or 2 fields and 2. when they'll go out of scope quickly, so it doesn't particularly matter what they are named). Another good time to fetch the array is when you're going to assign the results to member data right away, so they'll get meaningful names without the need of associating with the column names.

    [thanks to ralph l mayo]
    Last edited by JohnDubya; 02-23-2007 at 05:55 PM.

  • #5
    Super Moderator JohnDubya's Avatar
    Join Date
    Nov 2006
    Location
    Missouri
    Posts
    634
    Thanks
    12
    Thanked 18 Times in 18 Posts

    Don't use eval() or extract()

    [1]
    While the use of eval() is something that has set off many a flame war with equally capable proponents, I personally fall on the side that thinks that eval() is inherently evil. Extract() is a no-no (though I think there can be little argument there).
    [thanks to firepages]


    [2]
    Just as in JavaScript, I have not found a single use for eval. This function can be safely ignored.
    [thanks to aedrin]


    [3]
    Don't use extract() for anything. It seems it was made for people incapable of understanding hashes.
    [thanks to ralph l mayo]

  • #6
    Super Moderator JohnDubya's Avatar
    Join Date
    Nov 2006
    Location
    Missouri
    Posts
    634
    Thanks
    12
    Thanked 18 Times in 18 Posts

    Avoid the use of globals

    [1]
    PHP Code:
    global $envCode
    Best practice: Avoid 'global' at all costs. It pollutes the global scope and allows for bad programming. If you need to define whether it is a test environment, do it like this.
    PHP Code:
    define('DEBUG'true); 

    if (
    DEBUG) { 
        echo 
    "var=".$var

    [thanks to aedrin]

    [2]
    About the global thing...

    I agree that the accepted "best practices" is not to use them, but when something is actually global, such as an environment variable, then my opinion is they are ok.

    But I do agree, using a "constant" rather than the keyword "global" is a better practice.
    [thanks to Fumigator]

    [3]
    The superglobals $_GET,$_POST,$_ENV etc are already global assuming you reference them that way, no need for globals at all.
    [thanks to firepages]

  • #7
    Super Moderator JohnDubya's Avatar
    Join Date
    Nov 2006
    Location
    Missouri
    Posts
    634
    Thanks
    12
    Thanked 18 Times in 18 Posts

    Coding style

    [1]
    There is no perfect, exact way to style your code. So if someone tells you an exact way to style your code, look them in the eye and say with emphatic confidence in your voice, "Suck it."

    There are many ways to organize your code, and many of them are pretty good. To make your code look organized, you can use tabs to indent levels of your code, or you can use spaces. When using curly brackets, you can put them on the same line as the statements, or you can put them on the next line. There are positives and negatives to just about every way of styling your code, so know what they are, and choose one.

    Coding Styles
    Instead of me typing out a whole explanation of the positives and negatives of using this or that coding style, I'm going to refer to two sites that have already done this in great detail. Remember, these are suggestions, not the exact way you have to do things.



    As you can see, there is no right way. The biggest thing you should be concerned about is being consistent and clean. Find a good way to style your code, so you and others can look at your code and easily see what's going on. And then do it...consistently. Trust me, you'll be thankful later on when you have to go back and do edits to the code.
    Last edited by JohnDubya; 02-24-2007 at 07:56 PM.

  • #8
    Super Moderator JohnDubya's Avatar
    Join Date
    Nov 2006
    Location
    Missouri
    Posts
    634
    Thanks
    12
    Thanked 18 Times in 18 Posts

    Naming conventions for classes, variables, etc.

    [1]
    The most important thing I could tell you about naming standards for variables is to be descriptive. It is much, much better to name a variable that contains someone's first name $first_name instead of $a. $a doesn't tell you anything about what it contains. It would be appropriate to use $a for a variable that is holding temporary information (such as a query), but overall, try to be as descriptive as possible.

    Variable Names
    When you give a variable a name, try to follow these basic principles:

    • Make your variable names all lowercase.
    • Insert _ instead of spaces (e.g. use $first_name instead of $FirstName).
    • Try to keep your variable names as short as possible, while maintaining clarity of what the variable holds. A general maximum number of characters is about 15.

    Variable Names: http://www.dagbladet.no/development/...rd/#stacknames
    Variable/Function Naming: http://area51.phpbb.com/docs/coding-...tml#namingvars

    Classes
    Class Names: http://www.dagbladet.no/development/...rd/#classnames
    Class Library Names: http://www.dagbladet.no/development/...d/#classlnames
    Class Attribute Names: http://www.dagbladet.no/development/...ard/#attrnames

    Functions
    Function Names: http://www.dagbladet.no/development/...andard/#cnames
    Variable/Function Naming: http://area51.phpbb.com/docs/coding-...tml#namingvars

    To read more about naming conventions for variables, classes, functions, etc., here are some links:

    http://www.dagbladet.no/development/...tandard/#names
    http://www.evolt.org/node/60247
    Last edited by JohnDubya; 02-24-2007 at 07:57 PM.

  • #9
    Super Moderator JohnDubya's Avatar
    Join Date
    Nov 2006
    Location
    Missouri
    Posts
    634
    Thanks
    12
    Thanked 18 Times in 18 Posts

    Quoting strings (with single or double quotes)

    [1]
    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 (you can use $variables in the string without doing anything special) 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.

    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 easier to read. Examples:

    PHP Code:
    // wrong 
    $str "This is a really long string with no variables for the parser to find.";

    do_stuff("$str");

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

    do_stuff($str);

    // Sometimes single quotes are just not right

    $post_url $phpbb_root_path 'posting.' $phpEx '?mode=' $mode '&amp;start=' $start;

    // Double quotes are sometimes needed to not overcroud the line with concentinations

    $post_url "{$phpbb_root_path}posting.$phpEx?mode=$mode&amp;start=$start"
    In SQL Statements mixing single and double quotes is partly allowed (following the guidelines listed here about SQL Formatting), else it should be tryed to only use one method - mostly single quotes.
    [from Coding Guidelines]

    [2]
    It is a good idea to use single quotes when you are echoing HTML code. It is much easier to use single quotes because you don't have to escape all the double quotes you use:

    PHP Code:
    //single quotes allow you to use double quotes with the attributes in the HTML code

    echo '<div id="content">Hello there.</div>';

    //if you used double quotes, you would have to escape all of them

    echo "<div id=\"content\">Hello there.</div>"
    And here's how to use variables while using single quotes or double quotes:

    PHP Code:
    /* with single quotes, you need to use what's called "concatenation" (stop the string 
    with a ' and use a . to link strings together...then you can start back the string again 
    (if you need to) with another . and then a ') */

    echo 'The name of my company is ' $company_name ' and my name is ' $first_name;

    /* since double quotes allow variable interpolation, you can use a $variable inside double 
    quotes easily */

    echo "The name of my company is $company_name and my name is $first_name.";

    /* if you need to, you can put curly brackets around the variable in the double quotes to 
    make sure nothing jacks with it */

    echo "The name of my company is {$company_name} and my name is {$first_name}."
    Last edited by JohnDubya; 02-24-2007 at 08:36 PM.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •