PHP 数据类型
PHP 支持八种原始类型(type)。
四种标量类型:
string(字符串)
integer(整型)
float(浮点型,也作 double )
boolean(布尔型)
两种复合类型:
array(数组)
object(对象)
两种特殊类型:
resource(资源)
NULL(空)
查看变量类型
通过 gettype() 函数可以方便的查看某个变量的类型:
<?php
$var_bool = TRUE; // a boolean
$var_str = "foo"; // a string
$var_int = 12; // an integer
echo gettype($var_bool); // 输出 boolean
echo gettype($var_str); // 输出 string
echo gettype($var_int); // 输出 integer
?>
提示
由于历史原因,如果是 float 类型数据,gettype() 函数返回的是 double,而不是 float 。
如果想查看某个表达式的值和类型,请使用用 var_dump() 函数。
判断变量类型
如果想通过判断变量类型来确定下一步逻辑动作,不要使用 gettype() ,而使用 is_type 系列函数:
<?php
$var_int = 12;
// 如果 $var_int 是 int 类型,这进行加法
if (is_int($var_int)) {
$var_int = $var_int+4;
}
echo $var_int; // 输出 16
?>