本文出自:鍵盤語言

 


禁止使用者執行某些 PHP 指令
剛剛有朋友在問我 PHP 程式中 ,「單引號」與「雙引號」到底有而差別呢?

結論:
其實在 PHP 程式碼編譯的過程中 ,處理 單引號 ( ' ) 與 雙引號 ( " ) 時,是不同的處理方式的。
原因在於 PHP 會編譯「雙引號」字串內的變數,而「單引號」則視為純字串輸出,也就是 PHP 不會處理單引號內的內容,也因如此為什麼會有人說用單引號會讓 PHP 執行速度比較快,就是此因。


關於這問題參考以下程式範例,會更清楚

    $var = $value; // ok
    $var = "$value"; // ok, but double quotes are not necessary
    $var = '$value'; // will not work (single quotes will not allow parsing)

    ('.' the period adds/connects variables, functions, etc. together.
    Oftentimes programmers will leave spaces around the ' . ' to make
    things easier to read.)

    $var = 'This is the ' . $value . ' of things.'; // ok - preferred
    technique
    $var = "This is the $value of things."; // ok, but harder to read/debug
    $var = 'This is the $value of things.'; // will not parse $value
    $var = This is the $value of things.; // error

    $var = $array['name']; // ok, generally the preferred technique
    $var = $array["name"]; // ok, but why use double quotes if they are not
    necessary?
    $var = "$array[name]"; // ok, but harder to read/debug - poor coding
    style

    $var = 'Name: ' . $array['name']; // ok - preferred technique
    $var = "Name: $array[name]"; // ok, but harder to read/debug - poor
    coding style
    $var = "Name: $array["name"]"; // error
    $var = "Name: $array['name']"; // error

    exampleFunction($value); // ok
    exampleFunction("$value"); // ok, but double quotes are not necessary
    exampleFunction('$value'); // will not parse $value

備註:
 \n:換行(newline)
 \r:送出 CR(carriage)
 \t:跳位(Tab)
 \\:反斜線(backslash)
 \$:錢字號(dollar sign)
 \":雙引號(double-quote)
 \[0-7]{1,3}:八進位表示法的 regular expression
 \x[0-9A-Fa-f]{1,2}:十六進位表示法的 regular expression

原始文件來自於:
10 Tips That Every PHP Developer Should Know, Part 2

 

arrow
arrow
    全站熱搜

    正義的胖虎 發表在 痞客邦 留言(0) 人氣()