PHP学习(4)——数据类型

来源:互联网 发布:淘宝专业差评怎么找 编辑:程序博客网 时间:2024/05/16 10:59

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:  booleanecho gettype($a_str)."<br>";  // prints out:  stringecho gettype($an_int)."<br>";  // prints out:  integerecho gettype($a_float)."<br>";  // prints out:  double// If this is an integer, increment it by fourif (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);?>

输出:

booleanstringintegerdoublean_int = 12an_int = 16String: foofloat(3.14) bool(true) string(3) "foo" int(16)

php手册中对gettype()的解释(请放大查看☺):
这里写图片描述

每种类型的具体使用,请参考PHP的官方手册,我这里也只是抛砖引玉。

0 0
原创粉丝点击