Page 114 - Beginning PHP 5.3
P. 114
Part II: Learning the Language
Of course, if you don ’ t want to use curly brackets you can always create the string by concatenating the
values together:
$myArray[“age”] = 34;
echo “My age is “ . $myArray[“age”]; // Displays “My age is 34”
Using Your Own Delimiters
Although quotation marks make good delimiters for string literals in most situations, sometimes it
helps to be able to use your own delimiter. For example, if you need to specify a long string containing
lots of single and double quotation marks, it ’ s tedious to have to escape many quotation marks within
the string.
You can use your own delimiters in two ways: heredoc syntax and nowdoc syntax. Heredoc is the
equivalent of using double quotes: variable names are replaced with variable values, and you can use
escape sequences to represent special characters. Nowdoc works in the same way as single quotes: no
variable substitution or escaping takes place; the string is used entirely as - is.
Heredoc syntax works like this:
$myString = < < < DELIMITER
(insert string here)
DELIMITER;
DELIMITER is the string of text you want to use as a delimiter. It must contain just letters, numbers, and
underscores, and must start with a letter or underscore. Traditionally, heredoc delimiters are written in
uppercase, like constants.
Nowdoc syntax is similar; the only difference is that the delimiter is enclosed within single quotes:
$myString = < < < ’DELIMITER’
(insert string here)
DELIMITER;
Here ’ s an example of heredoc syntax in action:
$religion = ‘Hebrew’;
$myString = < < < END_TEXT
“’I am a $religion,’ he cries - and then - ‘I fear the Lord the God of
Heaven who hath made the sea and the dry land!’”
END_TEXT;
echo “ < pre > $myString < /pre > ”;
This example displays the following output:
“’I am a Hebrew,’ he cries - and then - ‘I fear the Lord the God of
Heaven who hath made the sea and the dry land!’”
76
9/21/09 8:53:40 AM
c05.indd 76 9/21/09 8:53:40 AM
c05.indd 76