首頁  >  文章  >  後端開發  >  php中單引號與雙引號有什麼差別?

php中單引號與雙引號有什麼差別?

青灯夜游
青灯夜游原創
2020-07-16 15:05:593599瀏覽

php中單引號與雙引號的差別:雙引號裡面的欄位會經過編譯器解釋,然後再當作HTML程式碼輸出;單引號裡面的欄位不進行解釋,會直接輸出。單引號不需要考慮變數的解析,速度比雙引號快。

php中單引號與雙引號有什麼差別?

在PHP中,我們可以使用單引號或雙引號來表示字串。不過我們身為開發者,應該要了解其中的差異。

1、對內容的解析不同

""雙引號裡面的欄位會經過編譯器解釋,然後再當作HTML程式碼輸出。

''單引號裡面的欄位不進行解釋,會直接輸出。 【相關推薦:PHP教學

<?php
$age = 20;
$str1 = &#39;I am $age years old&#39;;
$str2 = "I am $age years old";
echo $str1,&#39;<br />&#39;; // I am $age years old 
echo $str2,&#39;<br />&#39;; // I am 20 years old;
?>

2、解析速度不同

單引號不需要考慮變數的解析,速度比雙引號快。推薦用單引號,有的時候雙引號也比較好用,例如在拼湊sql 語句

#反斜線

//使用单引号
echo &#39; this \n is \r the blog \t of \\ zhoumanhe \\&#39;; 
//上面使用单引号输出的值是 this \n is \r the blog \t of \ zhoumanhe \  
echo &#39;&#39;;
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=&#39;abc&#39;;

SQL語句可以寫成:

SQLstr = “select * from abc_table where user _name= ‘abc&#39;” ;

假設查詢條件中使用的是變量,例如:

$user_name = $_REQUEST[&#39;user_name&#39;]; //字符串变量

$user=array (”name”=> $_REQUEST[&#39;user_name‘,"age"=>$_REQUEST[&#39;age&#39;];//数组变量

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 =&#39; ” . $user _name . ” ‘ “;
SQLstr=”select * from abc_table where user_name =&#39; ” . $user["name"] . ” ‘ “;

SQLstr可以分解為以下3個部分:

1:”select * from table where user_name = ' ” //固定SQL語句

2:$user //變數

3:” ' ” 

# PHP引號使用原則

1.字串的值用引號

2.PHP中盡量用單引號,HTML程式碼全部用雙引號

3.在包含變數的時候,用雙引號可以簡化操作

4.複雜的情況下用大括號包起來

PHP引號還有一個用處就是,有的時候需要用php生成文字文件,換行符號\n需要用雙引號才能好使,單引號則會直接把\n當成字元輸出。

以上是php中單引號與雙引號有什麼差別?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn