Home >Backend Development >PHP Tutorial >The difference between single quotes and double quotes in PHP

The difference between single quotes and double quotes in PHP

巴扎黑
巴扎黑Original
2016-12-07 15:51:031134browse

In PHP, you can use single quotes or double quotes to define a string. In ordinary use, there is no breakdown of the differences between the strings defined by these two symbols. Today I wrote a few lines of code as an example of "pass-by-reference assignment". In this code, both single quotes and double quotes are used to define strings (please pay attention to the fourth and sixth lines in the code snippet below). Execute Then something wonderful happened.

$var1="ChrisMao";//Assignthevalue"ChirsMao"to$var1
$var2=&$var1;//Reference$var1via$var2
echo'Thevalueof$var2is:' ,$var2,"
";//$var2and$var1havethesamevalue"ChrisMao"
$var2='mynameis$var2';//Modify$var2,thesametime$var1wasmodified
echo'Thevalueof$var1is: ',$var1,"
";//Thevalueof$var1is"mynameis$var2"
$var2="myNewnameis$var1";//Modify$var2,thesametime$var1wasmodified
echo'< ;b>Thevalueof$var2is:',$var2,"
";//Thevalueof$var1is"myNewnameismynameis$var2"
echo'Thevalueof$var1is: ',$var1,"
";//Thevalueof$var1is"myNewnameismynameis$var2"

The picture below is a screenshot of the execution result

The difference between single quotes and double quotes in PHP

I wonder if you have discovered anything after seeing this result. In the fourth and sixth lines of the code, the same variable name as in the code segment appears in the string on the right side of the assignment statement, except that one sentence uses single quotes and the other uses double quotes. Before execution, the expected output should be to output the variable name as a string instead of outputting the variable value. But after execution, it was found that the output was different from previous expectations. An assignment using single quotes will output the variable name in the string as it is, while an assignment statement using double quotes will replace the variable name with the actual value of the variable and output it.

I turned back to the chapter explaining string variables and read it carefully. I suddenly found that this phenomenon has been described in the book: the most important thing about double-quoted strings is that the variable name will be replaced by the variable value. It’s all the fault of not reading carefully!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:PHP date operationsNext article:PHP date operations