PHP: String Syntax, Heredoc
String can be quoted by a single quote.
<?php echo 'sweet home';
String can also be quoted using a double quote. When using double quote, any variables in the form $variableName
or ${variableName}
will be evaluated and its value used.
<?php $x = 3; echo "I bet you\n ${x} dollars"; /* output: I bet you 3 dollars */
Escape character sequence such as {\n, \r, \t} will also be interpreted when using double quote.
Heredoc and Nowdoc: Quoting Long Text
If you have a large block of text, you can use a form called “heredoc”.
You start the quote delimiter by <<<randomLetterSequence
and end it by the same letter sequence, followed by a semicolon, on a line by itself. Example:
<?php $herName = 'Alice'; $longText = <<<HHHHH 'and what is the use of a book,' thought $herName 'without pictures or conversation?'. HHHHH; echo $longText;
The output of above is this:
'and what is the use of a book,' thought Alice 'without pictures or conversation?'.
Note that in the above, we used this random string: HHHHH
for the delimiter. The ending delimiter must be exactly that followed by a semicolon, on a line by itself. No other chars can be there.
Heredoc is especially useful for large block of text (such as a template) that may itself contain many single quotes or double quotes.
Variables inside heredoc will still be interpreted (replaced by their values). Same for escape sequences (For example, {\n, \t, …}).
Nowdoc: Literal Quoting
To not have variables interpreted, use a form called “nowdoc”. The syntax is the same as heredoc, except you start it like this <<<'anyLetterSequence'
. Example:
<?php $herName = 'Alice'; $longText = <<<'HHHHH' 'and what is the use of a book,' thought $herName 'without pictures or conversation?'. HHHHH; echo $longText;
The output of above is this:
'and what is the use of a book,' thought $herName 'without pictures or conversation?'.
Patreon me $5. Ask me question on patreon