Why is '…' concatenating two numbers in my code?

自作多情 提交于 2019-12-30 05:55:08

问题


I have the following code snippet where I don't really understand its output:

echo 20...7;

Why does this code output 200.7?

From what I know ... is the splat operator, which it is called in ruby, that lets you have a function with a variable number of arguments, but I don't understand what it does here in the context with echo.

Can anyone explain what exactly this code does?


回答1:


No this is not the splat/unpacking operator, even thought it might seem like it is. This is just the result of the PHP parsing process. Already writing your code a bit different might clear some confusion:

echo  20.           .           .7;
#       ↑           ↑           ↑
#    decimal  concatenation  decimal
#      dot         dot         dot

Now you have to know that .7 is 0.7 and you can omit the 0 in PHP as described in the syntax for float numbers:

DNUM          ([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-9]*)

So PHP just concatenates those two numbers together and while doing this PHP's type juggling will silently convert both numbers to strings.

So in the end your code is equivalent to:

echo "20" . "0.7";
//Output: "200.7"


来源:https://stackoverflow.com/questions/44023765/why-is-concatenating-two-numbers-in-my-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!