欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

PHP中的数据类型(1)_PHP教程

程序员文章站 2022-04-03 17:13:24
...
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 integerecho gettype($bool); // prints out "boolean"echo gettype($str);  // prints out "string"// If this is an integer, increment it by fourif (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 booleanif ($action == "show_version") {   echo "The version is 1.23";}// this is not necessary...if ($show_separators == TRUE) {   echo "
n";}// ...because you can simply typeif ($show_separators) { echo "
n";}

转换为布尔值

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

参见类型戏法。

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

布尔值 FALSE

整型值 0(零)

浮点型值 0.0(零)

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

没有成员变量的数组

没有单元的对象

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

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

<?phpecho 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)?> 

1

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/446741.htmlTechArticlePHP 支持八种原始类型。 四种标量类型: 布尔型(boolean) 整型(integer) 浮点型(float)(浮点数,也作“double”) 字符串(string) 两种...