php 中数据类型的获取和设置主要采用方法:gettype( ) settype( )
上一篇php 介绍中说过,php 中有 八大数据类型:
四种标量类型:boolean (布尔型) integer (整型) float (浮点型, 也称作 double) string (字符串)
两种复合类型:array (数组) object (对象)
两种特殊类型:resource (资源) NULL (NULL)
这里主要研究8大类型相互转换可以采用哪些方法
当前类型 | 可转换类型 | 不可转换类型 |
array | boolean float integer null object string | resource |
string | boolean float integer null array | resource |
float | string boolean integer null object array | resource |
interger | string boolean double null object array | resource |
boolean | string integer null object array | resource |
object | string null boolean(true) array | resource float integer |
1)array
这里 array 转换为 string 采用 implode 方法:第一个参数是连接符
$str=implode(",",$arr);
2) string
string 转换为 Integer 时,若内容为非数字,强制转换后值为0;内容为小数强制取整;转换为array 时,使用settype 将数组的全部内容作为第一项输出;转换为 array 时,采用explode 方法,第一个参数根据字符串特点采用的切割符
$str=explode(" ",$str);
3)float
强制转换为array 时,用settype 和 explode 都是只能作为第一项。不过一般没人这么干
4)integer
各项特性与float 相同
5)boolean
转换为float 、Integer 时:true :1 false: 0,转为object、string 时,true : 1 false :空
6)object
转换为boolean时,对象内属性、方法为空时,都为1;转换为 string 时,用 json_encode(被转换的对象)
7)null
任何类型都可以转换为null
8)resource
主要由专门的函数来建立和使用的,例如打开文件、数据连接、图形画布,不与任意类型相互转换