Home > Article > Backend Development > The difference between single quotes and double quotes in PHP
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'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
I don’t know everyone Did you find 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!