PHP 支持 8 种原始数据类型。
四种标量类型:(标量类型即为基本类型)
- boolean(布尔型)
- integer(整型)
- float(浮点型,也称作 double) (由于历史原因,float也叫作double,php中没有单精度和双精度之分)
- string(字符串) (字符串类型在PHP中属于标量类型,在Java中属于类类型)
两种复合类型:
- array(数组)
- object(对象)
最后是两种特殊类型:
- resource(资源)
- NULL(无类型)
变量的类型通常不是由程序员设定的,确切地说,是由 PHP 根据该变量使用的上下文在运行时决定的。
如果想查看某个表达式的值和类型,用 var_dump() 函数。
如果只是想得到一个易读懂的类型的表达方式用于调试,用 gettype() 函数。要查看某个类型,不要用 gettype(),而用 is_type 函数。
例子:
<?php
$a_bool = TRUE; // a boolean
$a_str = "foo"; // a string
$a_str2 = 'foo'; // a string
$an_int = 12; // an integer
$a_float = 3.14; // a float(double)
echo gettype($a_bool)."<br>"; // prints out: boolean
echo gettype($a_str)."<br>"; // prints out: string
echo gettype($an_int)."<br>"; // prints out: integer
echo gettype($a_float)."<br>"; // prints out: double
// If this is an integer, increment it by four
if (is_int($an_int)) {
echo "an_int = ".$an_int."<br>";
$an_int += 4;
echo "an_int = ".$an_int."<br>";
}
// If $bool is a string, print it out
// (does not print out anything)
if (is_string($a_str)) {
echo "String: $a_str"."<br>";
}
echo var_dump($a_float, $a_bool, $a_str, $an_int);
?>
输出:
boolean
string
integer
double
an_int = 12
an_int = 16
String: foo
float(3.14) bool(true) string(3) "foo" int(16)
php手册中对gettype()的解释(请放大查看☺):
每种类型的具体使用,请参考PHP的官方手册,我这里也只是抛砖引玉。