PHP Strings
Interpolating Functions and Expressions Within Strings
Problem
You want to include the results of executing a function or expression within a string.
Solution
Example String concatenation
print 'You have '.($_POST['boys'] + $_POST['girls']).' children.';
print "The word '$word' is ".strlen($word).' characters long.';
print 'You owe '.$amounts['payment'].' immediately.';
print "My circle's diameter is ".$circle->getDiameter().' inches.';
Discussion
You can put variables, object properties, and array elements (if the subscript is unquo‐
ted) directly in double-quoted strings:
print "I have $children children.";
print "You owe $amounts[payment] immediately.";
print "My circle's diameter is $circle->diameter inches.";
Interpolation with double-quoted strings places some limitations on the syntax of what
can be interpolated. In the previous example, $amounts['payment'] had to be written
as $amounts[payment] so it would be interpolated properly. Use curly braces around
more complicated expressions to interpolate them into a string. For example:
print "I have {$children} children.";
print "You owe {$amounts['payment']} immediately.";
print "My circle's diameter is {$circle->getDiameter()} inches.";
Direct interpolation or using string concatenation also works with heredocs. Interpo‐
lating with string concatenation in heredocs can look a little strange because the closing
heredoc delimiter and the string concatenation operator have to be on separate lines:
print <<< END
Right now, the time is
END
. strftime('%c') . <<< END
but tomorrow it will be
END
. strftime('%c',time() + 86400);
Also, if you’re interpolating with heredocs, make sure to include appropriate spacing
for the whole string to appear properly. In the previous example, Right now, the time
is has to include a trailing space, and but tomorrow it will be has to include leading
and trailing spaces.
No comments:
Post a Comment