Home > Article > Backend Development > PHP variable definition and variable substitution methods_PHP tutorial
There are two ways to replace variables into strings - the simple way and the complex way.
A simple way is to put the variable name in a double-quoted string or heredoc:
$who = 'Kilroy';
$where = 'here';
echo "$who was $where ”;
Kilroy was here
The complicated method is to enclose the variable to be replaced in curly brackets. This approach can be used to disambiguate or replace array lookups. The classic use of braces is to separate a variable name from the surrounding text:
$n = 12;
echo “You are the {$n}th person”;
You are the 12th person
If there are no curly braces, PHP will try to print out the value of the variable $nth.
Unlike some shell environments, variables in PHP strings will not be parsed repeatedly, but will only be parsed in double-quoted strings, and then the result will be used as the value of the string:
$bar = ' this is not printed';
$foo = '$bar'; // Single quotes
print("$foo"); // Double quotes
$bar
4.1.2 Using single quotes Surrounded Strings
Single-Quoted Strings
Strings enclosed in single quotes do not replace variables. Because string literals are enclosed in single quotes, the variable names are not parsed in the following string:
$name = 'Fred';
$str = 'Hello, $name'; / /single-quoted Surrounded by single quotes
echo $str;
Hello, $name
The only escape sequence available in a string enclosed by single quotes is ' (putting the single quote inside in a string enclosed in single quotes), \ (putting a backslash in a string enclosed in single quotes). Any other backslash will only be interpreted as a backslash:
$name = 'Tim O'Reilly'; // escaped single quote
echo $name;
$path = ' C:\WINDOWS'; //Escaped backslash
echo $path;
$nope = 'n'; //Not an escape sequence
echo $nope;
Tim O' Reilly
C:WINDOWS
n
4.1.3 Strings enclosed in double quotes
Double-Quoted Strings
Strings enclosed in double quotes will be variable parsed and allowed Use many escape sequences. Table 4-1 lists the escape sequences that PHP recognizes in strings enclosed in double quotes.
Table 4-1: Escape sequences in strings enclosed in double quotes
Escape sequence character meanings
”
Double quotes
n
Newline
r
Enter
t
Tab
\
Backslash
$
Dollar sign
{
Left brace
}
Right brace
[
Left bracket
]
Right bracket