PHP 5.3中++运算符的奇怪行为

Mic*_*ozd 11 php operators

观看以下代码:

$a = 'Test';
echo ++$a;
Run Code Online (Sandbox Code Playgroud)

这将输出:

Tesu
Run Code Online (Sandbox Code Playgroud)

问题是,为什么?

我知道"你"是在"t"之后,但为什么它不打印"1"???

编辑: Becouse Zend书籍教授如下:

此外,递增或递减的变量将转换为适当的数值数据类型 - 因此,以下代码将返回1,因为字符串Test首先转换为整数0,然后递增.

sal*_*the 23

当处理字符变量而不是C的算术运算时,PHP遵循Perl的约定.例如,在Perl'Z'+ 1变成'AA',而在C'Z'+ 1变成'['(ord('Z')== 90,ord('[')== 91) .请注意,字符变量可以递增但不递减,即使只支持纯ASCII字符(az和AZ).

资料来源:http://php.net/operators.increment


Pet*_*tai 6

在PHP中你可以增加字符串(但你不能使用加法运算符"增加"字符串,因为加法运算符会导致字符串被强制转换为a int,你只能使用increment运算符来"增加"字符串!...见最后一个例子):

所以"a" + 1"b""z""aa"等.

因此,后"Test""Tesu"

在使用PHP的自动类型强制时,你必须注意上面的内容.

自动类型强制:

<?php
$a="+10.5";
echo ++$a;

// Output: 11.5
//   Automatic type coercion worked "intuitively"
?>
Run Code Online (Sandbox Code Playgroud)


没有自动类型强制!(递增一个字符串):

<?php
$a="$10.5";
echo ++$a;

// Output: $10.6
//   $a was dealt with as a string!
?>
Run Code Online (Sandbox Code Playgroud)



如果你想处理字母的ASCII序号,你必须做一些额外的工作.

如果要将字母转换为ASCII序列,请使用ord(),但这一次只能在一个字母上起作用.

<?php
$a="Test";
foreach(str_split($a) as $value)
{
    $a += ord($value);  // string + number = number
                        //   strings can only handle the increment operator
                        //   not the addition operator (the addition operator
                        //   will cast the string to an int).
}
echo ++$a;
?>
Run Code Online (Sandbox Code Playgroud)

实例

以上内容利用了字符串只能以PHP递增的事实.使用加法运算符无法增加它们.在字符串上使用加法运算符会导致它被强制转换为int,所以:

使用加法运算符不能"增加"字符串:

<?php
   $a = 'Test';
   $a = $a + 1;
   echo $a;

   // Output: 1
   //  Strings cannot be "added to", they can only be incremented using ++
   //  The above performs $a = ( (int) $a ) + 1;
?>
Run Code Online (Sandbox Code Playgroud)

以上将尝试将" Test" (int)添加到之前1.将" Test" 投射到(int)结果中0.


注意:您不能减少字符串:

请注意,字符变量可以递增但不递减,即使只支持纯ASCII字符(az和AZ).

以前的意思是echo --$a;实际打印Test而根本不更改字符串.