標籤:單引號 開發人員 雙引號 blog 字串 php
PHP教程:PHP中單引號與雙引號的區別分析
在PHP中,我們可以使用單引號或者雙引號來表示字串。不過我們作為開發人員,應該瞭解其中的區別。單引號與雙引號對於定義字元一個是可以解析變數一個是會把變數直接輸出來,同時單引號與雙引號在字元處理上單引號要優與雙引號
①轉義的字元不同
單引號和雙引號中都可以使用逸出字元(\),但只能轉義在單引號中引起來的單引號和轉義轉義符本身。如果用雙引號(“”)括起字串,PHP懂得更多特殊字元串的逸出序列。
1
②對變數的解析不同
單引號字串中出現的變數不會被變數值替代。即PHP不會解析單引號中的變數,而是將變數名原樣輸出。雙引號字串最重要的一點是其中的變數名會被變數值替代,即可以解析雙引號中包含的變數。
2
③解析速度不同
單引號不需要考慮變數的解析,速度比雙引號快.推薦用單引號.有的時候雙引號也比較好用,比如在拼湊sql 語句
反斜線
//使用單引號echo ‘ this \n is \r the blog \t of \\ zhoumanhe \\‘; //上面使用單引號輸出的值是 this \n is \r the blog \t of \ zhoumanhe \ echo ‘‘;echo ""; //使用雙引號echo "this \n is \r the blog \t of \\ zhoumanhe \\"; //上面使用雙引號輸出的值是 this is the blog of \ zhoumanhe \
使用sql
假設查詢條件中使用的是常量,例如:
select * from abc_table where user_name=‘abc‘;
SQL語句可以寫成:
SQLstr = “select * from abc_table where user _name= ‘abc‘” ;
假設查詢條件中使用的是變數,例如:
$user_name = $_REQUEST[‘user_name‘]; //字串變數
或
$user=array (”name”=> $_REQUEST[‘user_name‘,"age"=>$_REQUEST[‘age‘];//陣列變數
SQL語句就可以寫成:
SQLstr = “select * from abc_table where user_name = ‘ ” . $user_name . ” ‘ “;SQLstr = “select * from abc_table where user_name = ‘ ” . $user["name"] . ” ‘ “;
對比一下:
SQLstr=”select * from abc_table where user_name = ‘ abc ‘ ” ;SQLstr=”select * from abc_table where user_name =‘ ” . $user _name . ” ‘ “;SQLstr=”select * from abc_table where user_name =‘ ” . $user["name"] . ” ‘ “;
SQLstr可以分解為以下3個部分:
1:”select * from table where user_name = ‘ ” //固定SQL語句
2:$user //變數
3:” ‘ ”
附:大家也看到了 echo ‘
‘; html中的標籤在單引號和雙引號中都有效。
總結一下PHP引號使用原則
1.字串的值用引號
2.PHP中盡量用單引號,HTML代碼全部用雙引號
3.在包含變數的時候,用雙引號可以簡化操作
4.複雜的情況下用大括弧包起來
PHP引號還有一個用處就是,有的時候需要用php產生文字檔,分行符號n需要用雙引號才能好使,單引號則會直接把n當成字元輸出。
使用總結:在字串裡面不需要加入 變數 或者 單引號(‘)和反斜線(\) 時,盡量用單引號引字串,因為省去了雙引號檢查處理轉義和解析變數上面的時間。能用單引號盡量用單引號。
PHP教程:PHP中單引號與雙引號的區別分析