www.webdeveloper.com
Results 1 to 15 of 42

Thread: How to: write clean PHP

Threaded 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.

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