Rumah  >  Artikel  >  pembangunan bahagian belakang  >  php中单引号与双引号有什么区别?

php中单引号与双引号有什么区别?

青灯夜游
青灯夜游asal
2020-07-16 15:05:593585semak imbas

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当成字符输出。

Atas ialah kandungan terperinci php中单引号与双引号有什么区别?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel sebelumnya:php如何int转string?Artikel seterusnya:php中如何删除数组的键值