PHP 5.3中++运算符的奇怪行为 [英] Strange behaviour of ++ operator in PHP 5.3

查看:87
本文介绍了PHP 5.3中++运算符的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

观看以下代码:

$a = 'Test';
echo ++$a;

这将输出:

Tesu

问题是,为什么?

我知道"u"在"t"之后,但是为什么它不显示"1"?

I know "u" is after "t", but why it doesn't print "1" ???

编辑:因为Zend的书籍教了以下内容:

Becouse Zend books teach following:

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

Also, the variable being incremented or decremented will be converted to the appropriate numeric data type—thus, the following code will return 1, because the string Test is first converted to the integer number 0, and then incremented.

推荐答案

在PHP中,您可以增加字符串(但是您不能使用加法运算符来增加"字符串,因为加法运算符会导致将字符串强制转换为int,您只能使用递增运算符来增加"字符串!...请参见最后一个示例):

In PHP you can increment strings (but you cannot "increase" strings using the addition operator, since the addition operator will cause a string to be cast to an int, you can only use the increment operator to "increase" strings!... see the last example):

所以"z"出现"aa"之后"a" + 1"b",依此类推.

So "a" + 1 is "b" after "z" comes "aa" and so on.

所以"Test"出现后"Tesu"

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

You have to watch out for the above when making use of PHP's automatic type coercion.

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

// Output: 11.5
//   Automatic type coercion worked "intuitively"
?>


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

// Output: $10.6
//   $a was dealt with as a string!
?>


如果要处理字母的ASCII常规字符,则必须做一些额外的工作.

You have to do some extra work if you want to deal with the ASCII ordinals of letters.

如果要将字母转换为ASCII序号,请使用 ord( ) ,但是一次只能处理一个字母.

If you want to convert letters to their ASCII ordinals use ord(), but this will only work on one letter at a time.

<?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;
?>

在线示例

以上内容利用了字符串只能在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;
?>

以上将尝试在添加1之前将"Test"强制转换为(int).将"Test"强制转换为(int)会导致0.

The above will try to cast "Test" to an (int) before adding 1. Casting "Test" to an (int) results in 0.

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

请注意,字符变量可以递增但不能递减,即使如此,仅支持纯ASCII字符(a-z和A-Z).

Note that character variables can be incremented but not decremented and even so only plain ASCII characters (a-z and A-Z) are supported.

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

The previous means that echo --$a; will actually print Test without changing the string at all.

这篇关于PHP 5.3中++运算符的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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