为什么是句号,“."而不是加号“+",用于 PHP 中的字符串连接? [英] Why a full stop, "." and not a plus symbol, "+", for string concatenation in PHP?

查看:28
本文介绍了为什么是句号,“."而不是加号“+",用于 PHP 中的字符串连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么PHP的设计者决定使用句号/句号/."作为字符串连接运算符而不是更常见的加号+"?

它有什么好处,或者有什么理由吗?还是他们只是喜欢?:o)

解决方案

最明显的原因可能是 PHP 从 Perl 继承了很多语法——而 Perl 使用了一个点 (..

)code>) 用于字符串连接.

但是,我们可以更深入地研究它并找出为什么在 Perl 中实现它 - + 运算符最常用于数学方程 - 它仅用于在其中变量的语言中进行连接type 可以定义操作符的工作方式(简单解释,例子是C#)

var intAddition = 1 + 2;Console.WriteLine(intAddition);//打印 3var stringConcat = "1" + "2";Console.WriteLine(stringConcat);//打印12"

^ 如您所见,+ 运算符在 C# 中用于连接和加法.

<小时>

也许推理的层次较低,是由于逻辑门的布尔代数 - + 表示逻辑门中的 OR,而 . 用作 AND 运算符 - 这在涉及到时很有意义字符串连接.

有两个单独的运算符是有意义的,一个用于连接,一个用于加法 - 不幸的是,由于其他语言,这两者可能会混淆.

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)

解决方案

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.

这篇关于为什么是句号,“."而不是加号“+",用于 PHP 中的字符串连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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