www.webdeveloper.com
Page 1 of 3 123 LastLast
Results 1 to 15 of 42

Thread: How to: write clean PHP

Hybrid View

  1. #1
    Join Date
    Jun 2004
    Location
    4846′36″ N 910′48″ E
    Posts
    3,747

    How to: write clean PHP

    Hi,

    I thought i would spend a little time writing a bit about how to write clean PHP code (or clean code in general) as a few fellow webdevelopers (including myself) have been complaining about how most new users write horrible code.

    Badly written code is bad, that's primordial;

    Primo, it's bad for yourself, it is scientifically proved that it makes you depressive and have led several programmers to suicide.
    Messy code is an ideal hideout for wild coding errors: they will elegantly fade into the chaos, thus being hard to detect.
    (Nota Bene: An error can be a missing semi-colon or a missing parenthesis, etc..)

    Secondly, it's bad for the people who devote their time to help you. The main trigger for me writing this is this thread. I would help, but the code is too messy. If you want fellow programmers to be able to help you, you gotta give them a chance to understand the code at first glance. We won't spend our evening deciphering your code, really.

    How can you write cleaner code?

    First step will be to choose your favorite text editor. This step is important as you will most probably stick to this editor until the rest of your life
    Next thing to do, it look into the syntax highlighting settings (depending how personalisable the software is) and the indentation settings.

    the what?
    ..the indentation settings!

    That's one of the most important thing to say: INDENT!
    indent, tab..whatever you call it.

    Why would you do that..?!
    Indenting (correctly) will give you an almost godly overview of your code.
    In a matter of 1/12th of a second, you'll be able to tell where a chunck of code ends, where a function starts...

    an example
    (from the thread i mentioned above):

    bad:
    PHP Code:
    function isrequired($s$v) {
    global 
    $fields_required;
    if (
    in_array($v$fields_required)) {
    echo 
    $s;
    }

    better:
    PHP Code:
    function isrequired($s$v) {
        global 
    $fields_required;
        
        if (
    in_array($v$fields_required)) {
            echo 
    $s;
        }

    Can you see the difference? I hope you can
    I can assure you, you would see the difference at larger scales.

    Almost every programming, markup, styling language ignores tabs and whitespaces (except whitespace, hehe), so let's take advantage of that.


    (

    PS:
    the above code chunk could have been written like this:

    PHP Code:
    function isrequired($s$v) {

        global 
    $fields_required;
        
        if (
    in_array($v$fields_required)) {
        
            echo 
    $s;
            
        }

    )


    The Curly Braces Idyl:
    Curly braces are elegant, fragile beings. Their hearts can easily be broken, so they should be handled with the necessary care.
    One thing you should know: They always come in pair! (Failing to provide a fellow curly brace will generate an error, and break their hearts)

    If you write flat, dull code, it won't be hard to forget one, see:
    PHP Code:
    <?php
    $dir 
    "/etc/php5/";
    function 
    listdir($dir)
    {
    if (
    is_dir($dir))
    {
    if (
    $dh opendir($dir)) 
    {
    while ((
    $file readdir($dh)) !== false
    {
    echo 
    "filename: $file : filetype: " filetype($dir $file) . "\n";
    }
    closedir($dh);
    }
    }
    }
    ?>
    See! Which curly brace belongs to which?!
    How hard would it be to mistype and add or forget one if you already have 3 braces in a row (see last 4 lines in example code above)

    I'll now post the readable version of the code for you to see the difference in readability:

    PHP Code:
    <?php
    $dir 
    "/etc/php5/";

    function 
    listdir($dir)
    {
        if (
    is_dir($dir))
        {
            if (
    $dh opendir($dir)) 
            {
                while ((
    $file readdir($dh)) !== false
                {
                    echo 
    "filename: $file : filetype: " filetype($dir $file) . "\n";
                }
                
    closedir($dh);
            }
        }
    }
    ?>
    Now, if you wonder which one belongs to which one just follow a vertical line from any curly braces.

    You might have noticed that some people have the opening curly brace on the same line as the function name and the closing one under it:
    PHP Code:
    function fictional($parameter){
        
    // dream

    while other people will do:
    PHP Code:
    function fictional($parameter)
    {
        
    // dream

    That really is a matter of choice! (personally i much prefer the first one)


    Spaces and com(ets)as:
    As i said previously, use spaces!
    e.g.:
    PHP Code:
    list($drink,$color,$power)=$info
    instead, write:
    PHP Code:
    list($drink$color$power) = $info
    i usually leave one space after a coma, if it gets extra messy and long (for example in an INSERT query) i leave a space before and after the coma.


    Additional infos
    Don't post "I didn't write it!" as an excuse, if you are using code that you didn't write, need it, but find it awfully written, then correct it!

    Add the necessary comments, spaces and tabs!

    When creating custom functions, you might want to add a comment line above it, presenting it like the PHP manual:

    PHP Code:
    bool mail string tostring subjectstring message [, string additional_headers [, string additional_parameters]] ) 
    bool being the type returned (void, bool, int, resource, str, array, mixed)

    mail is obviously the function's name

    and the rest are the function's parameters (or pseudo parameter's name) and their respective types.
    Those in square brackets designate optional parameters. It is advised that they appear in your comments too.

    At last i will show you an example of a custom function
    (This is a function i used in an application, so it has quite limited use for you, just look at the structure, and pre-function comments)
    PHP Code:
    <?php
    ##############################################################
    #
    #                                 xml2array()
    #
    ##############################################################
    #(Short description)
    # xml2array() turn a preformatted XML file into an array
    #
    ##############################################################
    # array xml2array(str filename)
    function xml2array($xml_file){
        
    # loading file
        
    $xml simplexml_load_file($xml_file);
        
        if(!
    $xml){
            
    # could not load file
            
    return false;
        }


        
    # reading values from xml
        
    $dvd_list['userid'] = $xml->userid;

        
    $i 0;

        foreach(
    $xml->item as $item){
            
    $dvd_list[$i]['title'] = $item->title;
            
    $dvd_list[$i]['homeid'] = $item->homeid;
            
    $dvd_list[$i]['date'] = $item->date;
            
    $i++;
        }

        
    # returning array
        
    return $dvd_list;
    }
    ?>
    good coding!

    Cyril Hou
    Last edited by LiLcRaZyFuZzY; 04-12-2006 at 11:30 AM.

  2. #2
    Join Date
    Oct 2005
    Posts
    244
    Very nice!

    Hope people will actually read and do this.

    A mod should sticky this.

  3. #3
    Join Date
    Jan 2005
    Location
    Illinois
    Posts
    815
    Wow, great how to! It covers a wide range of good programming practices and is right to the point.
    Quote Originally Posted by LiLcRaZyFuZzY
    i usually leave one space after a coma, if it gets extra messy and long (for example in an INSERT query) i leave a space before and after the coma.
    Do you really go into coma's that often?

    --Steve

  4. #4
    Join Date
    Jan 2005
    Location
    Alicante (Spain)
    Posts
    7,742
    The bottom line is this: Each question deserves no more than a certain amount of time and effort from the few stalwart volunteers that answer the majority of the questions posed in this forum. Interesting and unusual questions of course deserve more time than the regular, mundane ones. If one of these volunteers looks at your code and sees that it would require an unreasonable amount of time and effort to correct because you haven't bothered to indent it properly or haven't used the [ PHP][/PHP] tags many of them will just move on to the next thread where the person asking the question has made more effort. I personally have completely stopped answering questions that are not encapsulated within [ PHP][/PHP] tags. If you want your questions to get the maximum coverage from the widest knowledge base take note of the recommendations in this thread; it's in your interest.

  5. #5
    Join Date
    Feb 2005
    Location
    Tauranga
    Posts
    2,062
    Agreed and very well done!

    I am in the same stance as Bokeh, If you dont use your VB Tags you wont get any pudding.. (Nor Help).

  6. #6
    Join Date
    Jan 2005
    Location
    Illinois
    Posts
    815
    This is all good advice for new users. The only problem is that new users will probably never read it, especially if stickied (word?). The sticky zone, it seems, is in almost every new user's blind spot.

    Here's a good suggestion for the forum that I think I read somewhere in one of the stickies here:
    A user should not be allowed to post until they have read (or at least visited) the "read this first" stickies and should be notified that failing to follow posting guidelines will likely result in an unanswered question.

    --Steve

  7. #7
    Join Date
    Feb 2005
    Location
    BC, Canada
    Posts
    1,098
    Here's a couple more things I try to stay true to:


    Take advantage of the <RETURN> key. For example:
    PHP Code:
    function _1 () {
        if (...) {
        }
        echo ...;
        while (...) {
        }
        echo ...;
        echo ...;
        if (...) {
        }

    is easier to read when it is written with a new line between each end bracket and the next line, such as:
    PHP Code:
    function _1 () {
        if (...) {
        }

        echo ...;
        while (...) {
        }

        echo ...;
        echo ...;
        if (...) {
        }

    .

    Also in the "make newlines" category, comes nasty, large arrays.
    PHP Code:
    // Original:
    $array = array(=> "zero"=> "one"=> "two"=> "three"=> "four"=> "five");

    // Recommended by me:
    $array = array( => "zero"
                    
    => "one"
                    
    => "two"
                    
    => "three"
                    
    => "four"
                    
    => "five"); 

  8. #8
    Join Date
    Jun 2004
    Location
    4846′36″ N 910′48″ E
    Posts
    3,747
    good call for the array spectre

    i see my "how to" disappear in page 2..

  9. #9
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,633
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  10. #10
    Join Date
    Jun 2004
    Location
    4846′36″ N 910′48″ E
    Posts
    3,747
    bump

  11. #11
    Join Date
    Aug 2004
    Location
    San Antonio, TX
    Posts
    564
    PHP Code:
      echo '.......' .
      
    '.......' .
      
    '.......' .
      
    '.......'
      
    ;

      print 
    '.......' .
      
    '.......' .
      
    '.......' .
      
    '.......'
      
    ;

    or use 
    " " instead of ' '

    also use this to enhance markup:

      echo 
      
    '<div id="one">' .
      
    '     <div id="two">' .
      
    '          ...Content Here...' .
      
    '     </div>' .
      
    '</div>'
      
    ;

    if 
    you want the new lines or returns just add "\n" after the concat op above like:

      echo 
      
    '<div id="one">' "\n" .
      
    '     <div id="two">' "\n" .
      
    '          ...Content Here...' "\n" .
      
    '     </div>' "\n" .
      
    '</div>' ."\n" .
      ;

    or 
    just make the echo with " " instead of ' ' and it will cut some of your code.

    this will really clean up the markup and I think is much nicer to read instead of:

    echo 
    "\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tFINALLY I GOT THE CONTENT OVER\n"

  12. #12
    Join Date
    Mar 2006
    Posts
    413
    Nice post:

    Although:

    Code:
    function Example() {
          //code goes here
    }
    
    function Example()
    {
         //code goes here
    }
    you state that you prefer the first method here, but also say that its better to match the curly brackets (as in the second example).

    The first method is highly annoying and difficult to read, EVERYONE should match their curly brackets. much nicer.

  13. #13
    Join Date
    Jan 2005
    Location
    Illinois
    Posts
    815
    Its up to the coder to decide which way they want to do it. Personally, I prefer the first method also. The second method requires too many extra lines that just aren't necessary and don't improve readability (IMO).

    --Steve

  14. #14
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,633
    Quote Originally Posted by balloonbuffoon
    Its up to the coder to decide which way they want to do it.
    Not if you're working for a company that has coding standards which state that you are specifically to do it one way or the other.

    Personally, I prefer the first method also. The second method requires too many extra lines that just aren't necessary and don't improve readability (IMO).

    --Steve
    Personally, I find the method with the opening brace on its own line much easier to read, especially when you start getting complex nestings of loop and if/else blocks - my eyes just seem to see the structure more easily that way. But what works best for me doesn't necessarily work better for anyone else.
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  15. #15
    Join Date
    Jan 2005
    Location
    Alicante (Spain)
    Posts
    7,742
    PHP Code:
    function gadget($gadgets)
    {
        foreach(
    $gadgets as $gadget)
        {
            if(
    false !== $gadget)
            {
                echo 
    $gadget;
            }
        }

    My vote goes to the above method. The whole point of indenting is so it is clear which opening curly brace is paired with which closing curly brace. When separated vertically without any offset I find it very clear.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles