Possible Duplicate:
Why is the php string concatenation operator a dot (.)?
I've always wondered -
Why does PHP use the 开发者_运维技巧. operator to concat strings instead of the + sign?
Is this some sort of way to improve script-evaluation performance?
Thanks
Because otherwise, what would happen in this case?
$str = "4";
$num = 2;
$result = $str + $num;
What if you wanted the result to be "42"?
Clarification
The above answers the question "why is there an operator .
in addition to the operator +
?". If the intended question was "why does operator +
not perform string concatenation?" (with the understanding that the would need to be another operator to take over the current behavior +
), then I 'll be happy to remove my answer in favor of a more relevant one.
After deciding that it (PHP) would do lots of autoboxing there was pretty much no other choice then to use 2 different operators for "adding" and "concating".
"+" for adding is obvious and @Gumbo explained why "." was chosen.
var_dump("12ab" + "34cd"); // 46
var_dump("12ab" . "34cd"); // "12ab34cd"
so you need to tell the language that you want it to do because it can do both :)
Other languages don't have that problem because they don't allow the implicit conversion from a string to an integer.
So if you write "4" + 2
the language would tell you that it can't to that and you'd need to write: intval("4") + 2
and it knows what to do.
Also see here
why-is-the-php-string-concatenation-operator-a-dot
Because Perl used the .
for string concatenation and PHP was highly influenced by Perl’s syntax.
精彩评论