为什么php字符串串联运算符是点(.)? [英] Why is the php string concatenation operator a dot (.)?

查看:75
本文介绍了为什么php字符串串联运算符是点(.)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中,字符串运算符点(.)用于连接字符串.例如:

In PHP, the string operator dot (.) is used to concatenate strings. For example:

$msg = "Hello there, " . $yourName;

点运算符似乎总是使人们(包括我自己)在他们第一次看到它时就感到困惑,特别是因为当您使用它来连接2个字符串时,该操作不会引发错误,而只是无声地"失败.在PHP和其他不使用此运算符的语言(例如JavaScript,Python等)之间进行切换时,这也是一个常见错误.

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"

谢谢!

推荐答案

我认为最好有一个不同的运算符,因为dot和plus的作用完全不同.

I think it is a good idea to have a different operator, because dot and plus do completely different things.

从非特定语言的角度来看,"a string" + "another string";的实际含义是什么?

What does "a string" + "another string"; actually mean, from a non specific language point of view?

是不是

  • 添加两个字符串的数值,或者
  • 连接两个字符串

您将假设它是第二个,但是在所有情况下(字符串除外),加号都用于数字加法.为什么?

You would assume it is the second, but a plus sign is used for numerical addition in all cases except Strings. Why?

另外,从松散类型的角度(PHP是)来看,一个php脚本

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.

这篇关于为什么php字符串串联运算符是点(.)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆