In PHP, the string operator dot (.) is used to concatenate strings. For example:
$msg = "Hello there, " . $yourName;
The dot operator always seems to confuse people (myself included) the first time they see it, especially since when you use it to concatenate 2 strings, the operation does not throw an error but just "silently" fails. It is also a common mistake when switching between PHP and other languages such as JavaScript, Python, etc that do not use this operator.
My question is, why does the language use the dot (.) operator instead of a more widely accepted operator such as plus (+)? Are there any historical reasons you can point to as to why this operator was selected? Is it just because the dot can cast other variable types to string? For example:
echo 1 . 2; //prints the string "12"
Thanks!
I think it is a good idea to have a different operator, because dot and plus do completely different things.
What does "a string" + "another string";
actually mean, from a non specific language point of view?
Does it mean
You would assume it is the second, but a plus sign is used for numerical addition in all cases except Strings. Why?
Also, from a loosely typed point of view (which PHP is), a php script
$myvar = 1;
$myvar2 = 2;
// would we expect a concatenation or addition?
$concat = $myvar + $myvar2;
The dot notation therefore specifies that it is clearly used for concatenation.
It is not that it is confusing, it is that it is not intuitive because all the other languages do it in a different way. And, is this a good reason to follow the trend? Doing things the way they are always done, is not always the right way.