在PHP中,你可以像这样递增一个字符:
$b = 'a'++;
我想知道从语言角度来看,为什么这样做是有效的?是因为PHP将字符解释成ASCII值,所以将其递增会使ASCII值增加1,然后就变成了字母表中的下一个字母吗?
看看这个:http://php.net/manual/en/language.operators.increment.php
PHP在处理字符变量的算术操作时遵循Perl的惯例,而不是C的。
例如,在PHP和Perl中 $a = 'Z'; $a++; 将$a变成'AA',而在C中 a = 'Z'; a++;将a变成'['('Z'的ASCII值为90,'['的ASCII值为91)。
请注意,字符变量可以递增但无法递减,并且仅支持纯ASCII字母和数字(a-z、A-Z 和 0-9)。递增/递减其他字符变量没有效果,原始字符串保持不变。
问题:我想知道的是,从语言角度来看,为什么它有效?
答案:为什么英文是从左到右书写,而阿拉伯文是从右到左呢?那是设计这种语言的人做出的决定。他们可能有自己的原因这样做。我坚信这是有意设计的,因为如果你进行算术加法($a+1),它不会按同样的方式工作。
$a = 'a';
echo $a++; // output: 'a' , a is echoed and then incremented to 'b'
echo ++$a; // output: 'c' , $a is already 'b' and incremented first and then becomes 'c'
echo $a+1; // output: '1' , When in an arathamatic operation a string value is considered 0
// in short '++' seems to have been given special intrepretation with string
// which is equivalent to
echo $a = chr(ord($a)+1); // output: 'd' , the ascii value is incremented
谢谢你的问题,我不知道 '++' 也可以应用于字符串。
'a'
,这是语法错误。即使你赋值$a = 'a'
然后执行$b = $a++
,$b
被赋的值也将是预递增值。(我知道这有点跑题了。) - Don't Panic