www.webdeveloper.com
Page 2 of 3 FirstFirst 123 LastLast
Results 16 to 30 of 42

Thread: How to: write clean PHP

  1. #16
    Join Date
    Nov 2003
    Location
    Canada
    Posts
    1,592
    I use pretty much the same format for writing PHP, with a few exceptions... for one, I don't use a space after between if and the condition:
    PHP Code:
    if($etc) { 
    Also, I think leaving a blank line every second line is pointless, doesn't like nice, and makes modifying it extremely difficult. Also, for short conditionals I write it like this
    PHP Code:
    $var = ($condition) ?
        
    true
        false

    (with tabs instead of spaces, as well)

    And finally, I use as few curly braces as possible. If there are only 1 or 2 functions to be carried out after a statement, I'll combine them (if 2) and omit the curly braces.

  2. #17
    Join Date
    Jan 2005
    Location
    Alicante (Spain)
    Posts
    7,736
    Quote Originally Posted by Daniel T
    If there are only 1 or 2 functions to be carried out after a statement, I'll combine them (if 2) and omit the curly braces.
    How can you have two functions in an if clause without curly braces.

  3. #18
    Join Date
    Oct 2005
    Location
    West Chester, PA
    Posts
    244
    Quote Originally Posted by bokeh
    How can you have two functions in an if clause without curly braces.
    PHP Code:
    if($conditionfunction1(function1($var)); 
    As for the Where-to-place-curly-braces debate, I recently switched to the "one true brace" (braces on there own line) after using the other method for quite a while, for a couple of reasons.
    1. It is easier to read, as you only need follow a straight line up, in order to determine where the matching brace is; as opposed to finding the control statement that it refers to.
    2. When I have complex control statements that require more than one line, I indent the second and later lines, so that it is clear that it is not a new statement. This required that I add a blank line between the end of the control statement and the first line of code. Even with the blank line, it took more than a glance to match the end brace to the start. Since I have the blank line anyway, I might as will put the brace there.
    Woohoo! It wor... er, wait, no it doesn't...
    PHP Coding Standard PHP Namespaces

  4. #19
    Join Date
    Jan 2005
    Location
    Alicante (Spain)
    Posts
    7,736
    Quote Originally Posted by aaronbdavis
    PHP Code:
    if($conditionfunction1(function1($var)); 
    That's only one statement! It is not possible to have more without curly braces.

  5. #20
    Join Date
    Oct 2005
    Location
    West Chester, PA
    Posts
    244
    Quote Originally Posted by bokeh
    That's only one statement! It is not possible to have more without curly braces.
    I realize that it is only one statement, but I think that it what he was getting at. In any case, I think it is bad practice anyway: what if you want to add more statements to the same conditional? If you forget to add the braces, you have just broken the program.
    Woohoo! It wor... er, wait, no it doesn't...
    PHP Coding Standard PHP Namespaces

  6. #21
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    18,936
    I think the over-arching, general rule here is: don't make formatting decisions based on reducing the number of keystrokes, but rather on how easy it will be for you and others to read and update the code at a later time. A few dozen extra carriage returns and curly braces will cost you a minute at most while typing out your code. Difficult to read code or code that leads to syntax errors when you go to update it later may cost you many minutes or even hours that you could have saved by spending just a little more time initially.
    "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

  7. #22
    Join Date
    Nov 2003
    Location
    Canada
    Posts
    1,592
    Quote Originally Posted by bokeh
    That's only one statement! It is not possible to have more without curly braces.
    Quote Originally Posted by Daniel T
    If there are only 1 or 2 functions to be carried out after a statement ...

  8. #23
    Join Date
    Nov 2009
    Posts
    268
    I'm Just another Dislexic guy I guess but this works for me. I want to be able to count the braces/brackets on each block? You can't always do that in small scroll areas though.
    PHP Code:
     
    function gadget($gadgets
    #brace 1
     
    foreach($gadgets as $gadget
    #brace 2

    if(false !== $gadget
    #brace 3

    echo $gadget;
    #forgot the space? 
    #brace 1
    #brace 2
    #brace 3
     
    $days=array(
     
    days[0]=>'Monday';
    days[1]=>'Tuesday';
    days[2]=>'Wedensday';
    days[3]=>'Thursday';
    days[4]=>'Friday';
    days[5]=>'Saturday';
    dsys[6]=>'Sunday';
     
    ); 
    Sorry about the lack of space between operators, I don't want to crunch that which doesn't need crunching. I do like the space before and after the statements though. Thanks guys. I was told that to learn a language you'd have to read and write it for at least ten years before you could be fluent at it and computer languages are not different in that regard for us Dislexic, it always helps to know when you are offending the site/forum administrators and volunteers. Most of them, thank heavens will let you know. ['php]'['/php]' is a good start.
    Last edited by THEFOOL; 05-04-2012 at 01:30 PM. Reason: #forgot the space?

  9. #24
    Join Date
    Apr 2010
    Posts
    227
    Curly brace not on the fucntion line is a waste of a line

    And my code gets long enough as it is!

    Great post!

    ps:

    This is how i prefer to write my SQL queries because they are so much easier to read this way IMHO..
    PHP Code:

            $query 
    "INSERT INTO `user_char` SET user='$this->user',
                                                  name='
    $this->name',
                                                  head='11',
                                                  body='10',
                                                  right_hand='5',
                                                  left_hand='12',
                                                  legs='',
                                                  pack='
    $pack',
                                                  skills='
    $skills',
                                                  health='100|100',
                                                  brawn='20',
                                                  stamina='1.5'
                                                  "


  10. #25
    Join Date
    Nov 2009
    Posts
    268
    Belrick, nice with the ',' seperation but the deep indent takes to much time in notepad and would force horizontal scrolling in most forums? The brace on the function line makes it harder for us dislexics to pair them off. Brace as in two pistols. Not to mention the forcing of scrolling in the forums again but that is what indenting does. I like to do without it.

  11. #26
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    18,936
    With a decent editor, you can use tabs for all the indents but then tell the editor how many spaces to use for displaying the indents in the editor, so that it suits your particular needs/tastes.

    As saved:
    Code:
    <?php
    function foo(PDO $pdo, $bar, $time)
    {
    [tab]$sql = "
    [tab][tab]SELECT
    [tab][tab][tab]foo_id,
    [tab][tab][tab]foo_name,
    [tab][tab][tab]foo_timestamp
    [tab][tab]FROM foo.bar
    [tab][tab]WHERE
    [tab][tab][tab]foo_name = :bar
    [tab][tab]AND
    [tab][tab][tab]foo_timestamp > :time
    [tab]";
    [tab]$stmt = $pdo->prepare($sql);
    [tab]if($stmt == false) {
    [tab][tab]throw new Exception("Prepare failed: ".print_r($pdo->errorInfo()));
    [tab]}
    [tab]$stmt->bindParam(':bar', $bar, PDO::PARAM_STR);
    [tab]$stmt->bindParam(':time', $time, PDO::PARAM_STR);
    [tab]if($stmt->execute() == false) {
    [tab][tab]throw new Exception("Query failed: ".print_r($stmt->errorInfo()));
    [tab]}
    [tab]return $stmt->fetchAll();
    }
    ]

    As I see it in Komodo Edit (with 4 spaces per indent tab in my settings):
    PHP Code:
    <?php
    function foo(PDO $pdo$bar$time)
    {
        
    $sql "
            SELECT
                foo_id,
                foo_name,
                foo_timestamp
            FROM foo.bar
            WHERE
                foo_name = :bar
            AND
                foo_timestamp > :time
        "
    ;
        
    $stmt $pdo->prepare($sql);
        if(
    $stmt == false) {
            throw new 
    Exception("Prepare failed: ".print_r($pdo->errorInfo()));
        }
        
    $stmt->bindParam(':bar'$barPDO::PARAM_STR);
        
    $stmt->bindParam(':time'$timePDO::PARAM_STR);
        if(
    $stmt->execute() == false) {
            throw new 
    Exception("Query failed: ".print_r($stmt->errorInfo()));
        }
        return 
    $stmt->fetchAll();
    }
    How I could view it in Komodo Edit if I changed the settings to 2 spaces per indent tab:
    PHP Code:
    <?php
    function foo(PDO $pdo$bar$time)
    {
      
    $sql "
        SELECT
          foo_id,
          foo_name,
          foo_timestamp
        FROM foo.bar
        WHERE
          foo_name = :bar
        AND
          foo_timestamp > :time
      "
    ;
      
    $stmt $pdo->prepare($sql);
      if(
    $stmt == false) {
        throw new 
    Exception("Prepare failed: ".print_r($pdo->errorInfo()));
      }
      
    $stmt->bindParam(':bar'$barPDO::PARAM_STR);
      
    $stmt->bindParam(':time'$timePDO::PARAM_STR);
      if(
    $stmt->execute() == false) {
        throw new 
    Exception("Query failed: ".print_r($stmt->errorInfo()));
      }
      return 
    $stmt->fetchAll();
    }
    "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

  12. #27
    Join Date
    Nov 2009
    Posts
    268

    Thumbs up How to: write clean PHP

    Right on NogDog, I still preffer this though, ie. no indent and space between statements.

    PHP Code:
    <?php 

    function foo(PDO $pdo$bar$time


    $sql 
    SELECT 
    foo_id, 
    foo_name, 
    foo_timestamp 
    FROM foo.bar 
    WHERE 
    foo_name = :bar 
    AND 
    foo_timestamp > :time 
    "


    $stmt $pdo->prepare($sql); 

    if(
    $stmt == false


    throw new 
    Exception("Prepare failed: ".print_r($pdo->errorInfo()));
     

        
    $stmt->bindParam(':bar'$barPDO::PARAM_STR); 
        
    $stmt->bindParam(':time'$timePDO::PARAM_STR); 
        
    if(
    $stmt->execute() == false

            
    throw new 
    Exception("Query failed: ".print_r($stmt->errorInfo())); 
        

        
    return 
    $stmt->fetchAll();
     
    }

  13. #28
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    18,936
    Quote Originally Posted by THEFOOL View Post
    Right on NogDog, I still preffer this though, ie. no indent and space between statements.
    I for one don't ever want to have to maintain your code.

    Well, actually, I'd just run my "beautifier" macro in Komodo and not have to worry about it.
    "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

  14. #29
    Join Date
    Jul 2009
    Location
    My house, sitting at the computer. Duh!
    Posts
    118
    One thing that I think is worth mentioning, and I've seen in some examples here already, is that SQL can and should span multiple lines. From what I've seen, a lot, if not most people tend to write it all on one line, which drives me crazy. I actually saw one dude use over 20 WHERE OR conditions all on one line.

    PHP Code:
    $sql '
        SELECT user_name
        FROM pc_users
        WHERE user_id = 2'


  15. #30
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    18,936
    Quote Originally Posted by ScottyBoy View Post
    One thing that I think is worth mentioning, and I've seen in some examples here already, is that SQL can and should span multiple lines. From what I've seen, a lot, if not most people tend to write it all on one line, which drives me crazy. I actually saw one dude use over 20 WHERE OR conditions all on one line.

    PHP Code:
    $sql '
        SELECT user_name
        FROM pc_users
        WHERE user_id = 2'

    It definitely saves time when you get an SQL error like "error near 'or' on line 20" versus "error near 'or' on line 1".
    "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

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