A string is series of characters.
A string literal can be specified in four different ways:
<?php echo 'this is a simple string'; // Single quoted echo "This is a string in double quotes"; // Double quoted $foo = <<<LABEL bar LABEL; echo $foo; // heredoc echo <<<'NOWDOC' Nowdoc string example:Backslashes are always treated literally, e.g. \\ and \'. NOWDOC; //Nowdoc ?>
Single quoted strings are treated almost literally.
<?php // Outputs: Hello world! echo 'Hello world!'; echo "<br>"; // Outputs: Hello Lautturi! echo 'Hello Lautturi!'; echo "<br>"; // Outputs: I\'ll be back. echo 'I\'ll be back.'; echo "<br>"; // Outputs: single backslash with newline character \n echo 'single backslash with newline character \\n'; // Outputs: This will not expand: \n a newline echo 'This will not expand: \n a newline'; // Outputs: Variables do not $expand echo 'Variables do not $expand'; ?>
<?php $str = "PHP Double quoted String"; echo "str:$str."."<br>"; echo "strs:$strs."."<br>"; // Invalid. $strs is undefined echo "strs:${str}s."."<br>"; // Valid. the $ must immediately follows the {. ?>
Output:
str:PHP Double quoted String. strs:. strs:PHP Double quoted Strings.
The Complex (curly) syntax `${} is used to get the value of a var named by a return value.
<?php $var = "str"; $str = "PHP Variable parsing syntax"; // Output:PHP Variable parsing syntax echo ${$var}; // ${str} => $str echo "<br>"; $fruit = "apple"; $price_apple = 30; // Output:Price:30 echo "Price:". ${'price_'.$fruit} ."<br>"; ?>
When a string is specified in double quotes or with heredoc, variables are parsed within it. (replaced with their values), but Single quoted strings are treated almost literally.
Single quoted vs Double quoted
<?php $variable = "PHP strings"; echo 'The $variable value will not print.'."<br>"; // The $variable value will not print. echo "The value $variable will print."."<br>"; // The value PHP strings will print. ?>
heredoc syntax is: <<< .After this operator, an identifier(LABEL) is provided, then a newline.
Then multiple lines string follows.Finally the same identifier(LABEL) again to close the quotation.
<?php $foo = <<<LABEL string multiple lines LABEL; var_dump($foo); // heredoc ?>
Output:
string(23) "string multiple lines"
Notes
$foo = <<<LABEL(newline)
Valid
LABEL;(whitespace)
Invalid
LABEL;
Valid
(whitespace)LABEL;
Invalid, Identifier must not be indented
<?php $str = <<<EOT Example of string spanning multiple lines using heredoc syntax. EOT; // EOT; // Invalid, Identifier must not be indented //EOT;; // Invalid, the semicolon(;) could not follows any character echo $str
Nowdocs are to single-quoted strings what heredocs are to double-quoted strings.
The differences are:
<<<"EOT"
,<<<EOD
.<<<'EOT'
.<?php echo <<<'EOD' Example of string spanning multiple lines using nowdoc syntax. Backslashes(\) are always treated literally, e.g. \\ and \'. EOD;