php中,int為整形
一個 integer 是集合 Z = {..., -2, -1, 0,
1, 2, ...} 中的一個數。
整型值可以使用十進位,十六進位或八進位表示,前面可以加上可選的符號(- 或者 +)。
八進位表示數字前必須加上 0
(零),十六進位表示數字前必須加上 0x
。
Example #1 整數文字表達
<?php$a
=
1234
;
// 十進位數
$a
= -
123
;
// 負數
$a
=
0123
;
// 八位元 (等於十進位 83)
$a
=
0x1A
;
// 十六進位數 (等於十進位 26)
?>
整型(integer)
的形式描述:
decimal : [1-9][0-9]*
| 0
hexadecimal : 0[xX][0-9a-fA-F]+
octal : 0[0-7]+
integer : [+-]?decimal
| [+-]?hexadecimal
| [+-]?octal
整型數的字長和平台有關,儘管通常最大值是大約二十億(32 位有符號)。PHP 不支援不帶正負號的整數。Integer
值的字長可以用常量PHP_INT_SIZE
來表示,自
PHP 4.4.0 和 PHP 5.0.5後,最大值可以用常量PHP_INT_MAX
來表示。
注意:
如果向八位元傳遞了一個非法數字(即 8 或 9),則後面其餘數字會被忽略。
Example #2 八位元的怪事
<?phpvar_dump
(
01090
);
// 八進位 010 = 十進位 8
?>
整數溢出
如果給定的一個數超出了 integer
的範圍,將會被解釋為 float
。同樣如果執行的運算結果超出了 integer
範圍,也會返回 float
。
<?php$large_number
=
2147483647
;
var_dump
(
$large_number
);
// 輸出為:int(2147483647)
$large_number
=
2147483648
;
var_dump
(
$large_number
);
// 輸出為:float(2147483648)
// 同樣也適用於十六進位表示的整數: 從 2^31 到 2^32-1:
var_dump
(
0xffffffff
);
// 輸出: float(4294967295)
// 不適用於大於 2^32-1 的十六進位表示的數:
var_dump
(
0x100000000
);
// 輸出: int(2147483647)
$million
=
1000000
;
$large_number
=
50000
*
$million
;
var_dump
(
$large_number
);
// 輸出: float(50000000000)
?>
要明確地將一個值轉換為 integer
,用 (int)
或
(integer)
強制轉換。不過大多數情況下都不需要強制轉換,因為當運算子,函數或流程式控制制需要一個 integer
參數時,值會自動轉換。還可以通過函數 intval()
來將一個值轉換成整型。
當從浮點數轉換成整數時,將向零
取整。
如果浮點數超出了整數範圍(通常為 +/- 2.15e+9 =
2^31
),則結果不確定,因為沒有足夠的精度使浮點數給出一個確切的整數結果。在此情況下沒有警告,甚至沒有任何通知!
Warning
決不要將未知的分數強制轉換為 integer
,這樣有時會導致不可預料的結果。
<?php
echo (int) ( (
0.1
+
0.7
) *
10
);
// 顯示 7!
?>
要非常注意整數溢出,當正數溢出時,會裝換為float型,當附屬溢出時則根據作業系統的不同來有不同的操作。
如:
<?php
echo
(int)-
3000000000
;
// a 32bit negative overflow
?>
在windows下和ubuntu下結果為
1294967296,但是在FreeBSD下為-2147483648。
使用時要小心,當用整數轉換來測試一些評估,看它是否為正整數與否。你可能會得到意外的行為。
<?php
error_reporting
(
E_ALL
);
require_once
'Date.php'
;
$date
= new
Date
();
print
"/$date is an instance of "
.
get_class
(
$date
) .
"/n"
;
$date
+=
0
;
print
"/$date is now
$date
/n"
;
var_dump
(
$date
);
$foo
= new
foo
();
print
"/$foo is an instance of "
.
get_class
(
$foo
) .
"/n"
;
$foo
+=
0
;
print
"/$foo is now
$foo
/n"
;
var_dump
(
$foo
);
class
foo
{
var
$bar
=
0
;
var
$baz
=
"la lal la"
;
var
$bak
;
function
foo
() {
$bak
=
3.14159
;
}
}
?>
輸出結果為:
$date is an instance of Date
Notice: Object of class Date could not be
converted to int in /home/kpeters/work/sketches/ObjectSketch.php on line
7
$date is now 1
int(1)
$foo is an instance of foo
Notice:
Object of class foo could not be converted to int in
/home/kpeters/work/sketches/ObjectSketch.php on line 13
$foo is now
1
int(1)
這是因為對象首先被轉換為布爾值true,在加0時轉換為整形1。