I often have to assign large strings to variables. In the source code I preferably want to keep my lines within 80 characters.
Ideally I want to be able to lay these literal strings out on multiple lines.
What I want to avoid is using concatenation, or function calls (e.g. preg_replace()), to join multiple strings together in one. I don’t like the idea that I have to invoke language features in order to improve the style of my code.
Example of something I would like:
$text = <<<TEXT
Line 1
Line 2
Line 3
TEXT;
echo($text);
This should output:
Line1Line2Line3
Is this possible?
There are a few options:
Just concatenate (preferred)
Use
arrayconstructsUse
sprintf()Just concatenate:
The above code compiles into the following opcodes (which is what’s run):
As you can see, it builds the string by concatenating the first two lines, followed by the last line; in the end
~0is discarded. In terms of memory, the difference is negligible.This is what a single
echostatement would look like:Technically it’s faster because there are no intermediate steps, but in reality you won’t feel that difference at all.
Using
array:Using
sprintf():