PHP中的数据类型(1)

PHP 支持八种原始类型。

四种标量类型:

布尔型(boolean)

整型(integer)

浮点型(float)(浮点数,也作“double”)

字符串(string)

两种复合类型:

数组(array)

对象(object)

最后是两种特殊类型:

资源(resource)

NULL

为了确保代码的易读性,本手册还介绍了一些伪类型:

混和(mixed)

数字(number)

回馈(callback)

您可能还会读到一些关于“双精度(double)”类型的参考。实际上 double 和 float 是相同的,由于一些历史的原因,这两个名称同时存在。

变量的类型通常不是由程序员设定的,确切地说,是由 PHP 根据该变量使用的上下文在运行时决定的。

注: 如果你想查看某个表达式的值和类型,用 var_dump()。

注: 如果你只是想得到一个易读懂的类型的表达方式用于调试,用 gettype()。要查看某个类型,不要用 gettype(),而用 is_type 函数。以下是一些范例:

 

 

<?php
$bool = TRUE;  // a boolean
$str  = "foo";  // a string
$int  = 12;    // an integer

echo gettype($bool); // prints out "boolean"
echo gettype($str);  // prints out "string"

// If this is an integer, increment it by four
if (is_int($int)) {
   $int += 4;
}

// If $bool is a string, print it out
// (does not print out anything)
if (is_string($bool)) {
   echo "String: $bool";
}
?>  

如果你要将一个变量强制转换为某类型,可以对其使用强制转换或者 settype() 函数。

注意变量根据其当时的类型在特定场合下会表现出不同的值。更多信息见类型戏法。此外,你还可以参考 PHP 类型比较表看不同类型相互比较的例子昆明国防路医院

 布尔型

这是最简单的类型。boolean 表达了真值,可以为 TRUE 或 FALSE。

注: 布尔类型是 PHP 4 引进的。

语法

要指定一个布尔值,使用关键字 TRUE 或 FALSE。两个都是大小写不敏感的。

<?php
$foo = True; // assign the value TRUE to $foo
?>

通常你用某些运算符返回 boolean 值,并将其传递给流程控制。

// == is an operator which test
// equality and returns a boolean
if ($action == "show_version") {
   echo "The version is 1.23";
}

// this is not necessary...
if ($show_separators == TRUE) {
   echo "

\n";
}

// ...because you can simply type
if ($show_separators) {
   echo "

\n";
} 

转换为布尔值

要明示地将一个值转换成 boolean,用 (bool) 或者 (boolean) 来强制转换。但是很多情况下不需要用强制转换,因为当运算符,函数或者流程控制需要一个 boolean 参数时,该值会被自动转换。

参见类型戏法。

当转换为 boolean 时,以下值被认为是 FALSE:

布尔值 FALSE

整型值 0(零)

浮点型值 0.0(零)

空白字符串和字符串 "0"

没有成员变量的数组

没有单元的对象

特殊类型NULL(包括尚未设定的变量)

所有其它值都被认为是 TRUE(包括任何资源)。 

<?php
echo gettype((bool) "");        // bool(false)
echo gettype((bool) 1);        // bool(true)
echo gettype((bool) -2);        // bool(true)
echo gettype((bool) "foo");    // bool(true)
echo gettype((bool) 2.3e5);    // bool(true)
echo gettype((bool) array(12)); // bool(true)
echo gettype((bool) array());  // bool(false)
?> 

 

posted @ 2014-05-09 10:02  WDYE  阅读(251)  评论(0编辑  收藏  举报