Thread: String literals

    #1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2005
    Location
    Vancouver, WA, USA
    Posts
    397
    Rep Power
    189

    String literals


    I know all are acceptable:

    PHP Code:
    echo "My name is {$name}.";
    echo 
    'My name is ' $name '.';
    echo 
    sprintf('My name is %s.',$name); 
    I am interested in hearing arguments for and against the different methods. I normally use the first... It seems easiest to read, and is the fewest keystrokes.
    Thomas Tremain
  2. #2
  3. Transforming Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    14,113
    Rep Power
    9398
    Double quotes:
    - Pro: lets you put variables and other metacharacters in
    - Con: will try to interpret escapes and interpolated variables when you might not want it to (regular expressions and Windows filenames being good examples of that)
    - Con: most people like using double quotes in HTML attributes - those would have to be escaped which looks ugly

    Single quotes:
    - Pro: as close to a literal string as you can get in PHP, besides nowdoc
    - Con: no newlines, no tabs, etc.
    - Con: no variables

    printf/sprintf:
    - Pro: easy to read
    - Con: function call
    - Con: you can fall prey to XSS exploits like in this contrived example:
    PHP Code:
    printf("{$person} is %d years old"$_GET["age"]); 

IMN logo majestic logo threadwatch logo seochat tools logo