Making string concatenation readable in PHP
Probably all PHP developers know how to concatenate strings. The most popular method is using the .
-operator. For small concatenations using this operator works fine. When lots of strings or variables need to be combined it can become cumbersome.
Here's an example:
$logMessage = 'A '.$user->type.' with e-mailaddress '.$user->email.' has performed '.$action.' on '.$subject.'.';
Wow, my fingers hurt... While typing the most time is spent on making sure the quotes are open and closed on the right places. It also isn't very readable. Especially the .'.'
at the end make my eyes bleed.
A better way to create the string is to use the sprintf
-function.
This example produces the same string as the code above:
$logMessage = sprintf('A %s with email %s has performed %s on %s.', $user->type, $user->email, $action, $subject);
That's much better. This is much easier to type and you don't have to pay attention to opening an closing quotes. But my eyes still need to do a lot of work. To find out which string goes in which %s
-placeholder you have to switch watching the beginning and end of the line of code.
There is another option to concatenate strings. It uses curly braces. Let's take a look:
$logMessage = "A {$user->type} with e-mailaddress {$user->email} has performed {$action} on {$subject}."
In my mind this is much better. This option has the least amount of characters to type. Your eyes can just read the line of code from left to right to understand what's going on. Keep in mind that this only works when using the curly braces between a double quote. The first character after the opening curly braces should be a dollar-sign.
EDIT: The curly braces syntax works well if you only need to concatenate strings. As mentioned in the comments below this post, <a href="http://php.net/manual/en/function.sprintf.php">sprintf</a>
might be a better fit when concatenating some other type of variable.
What are your thoughts on "Making string concatenation readable in PHP"?