Why did the designers of PHP decide to use a full stop / period / "." as the string concatenation operator rather than the more usual plus symbol "+" ?
Is there any advantage to it, or any reason at all? Or did they just like to? :o)
1. Concatenation Operator ("."): In PHP, this operator is used to combine the two string values and returns it as a new string.
The "dot" is a string concatenator. That is, it helps you to combine strings together into another string.
If you concatenate Stings in loops for each iteration a new intermediate object is created in the String constant pool. This is not recommended as it causes memory issues.
The + (plus) operator is often overloaded to denote concatenation for string arguments: "Hello, " + "World" has the value "Hello, World" .
PHP's syntax is influenced by Perl, and .
is the string concatenation operator in Perl.
In a weakly typed language there are advantages to having a different string concatenation and numeric addition operators: which one you use will influence which type the language coerces the variables to.
As it happens, Perl 6 will use a tilde ~
instead of a dot .
for string concatenation, because .
will be used for object member access. So it seems the designers of Perl now think it was a bad choice.
Perhaps, in Perl and PHP's early, non-Object-Oriented days, it seemed like as good a choice as any. Maybe the designers of both languages never envisaged them becoming strong OO languages.
As for whether PHP will one day ditch its ->
member access syntax for .
, who knows?
The most obvious reason would probably be that PHP inherits a lot of its syntax from Perl - and Perl uses a dot (.
) for string concatenation.
But, we can delve deeper into it and figure out why this was implemented in Perl - the +
operator is most commonly used for mathematical equations - it's only used for concatenation in languages in which the variable type can define the way in which the operator works (simple explanation, example is C#)
var intAddition = 1 + 2; Console.WriteLine(intAddition); // Prints 3 var stringConcat = "1" + "2"; Console.WriteLine(stringConcat); // Prints "12"
^ As you can see, the +
operator is used both for concatenation and addition in C#.
Perhaps the reasoning goes lower level and is due to the boolean algebra of logic gates - +
means OR
in logic gates, whereas .
is used as the AND
operator - which makes sense when it comes to string concatenation.
It makes sense to have two separate operators, one for concatenation and one for addition - it's just unfortunate that these two can be mixed up due to other languages.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With