🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# 类型概述 PHP支持十种原始数据类型,包括四种标量类型、四中复合类型以及两种特殊的类型。PHP是一种弱类型的语言,所以不像其他语言一样要显示地声明变量的数据类型,变量是什么数据类型是在运行时PHP自己根据变量的值决定的,所以了解数据类型只是增加理解。 想要知道一个表达式的类型和值,可以使用[var_dump() ](http://php.net/manual/en/function.var-dump.php)函数,想要知道一个变量的类型,可以使用[gettype()](http://php.net/manual/en/function.gettype.php)函数,如果想要确认一个变量是否是某个数据类型,请使用 *is_type* 函数,type用你想要确认的那个数据类型代替。 Example #1 gettype()函数和is_type()函数的 ~~~ <?php $a_bool = TRUE; // a boolean $a_str = "foo"; // a string $a_str2 = 'foo'; // a string $an_int = 12; // an integer echo gettype($a_bool); // prints out: boolean echo gettype($a_str); // prints out: string // If this is an integer, increment it by four if (is_int($an_int)) { $an_int += 4; } // If $a_bool is a string, print it out // (does not print out anything) if (is_string($a_bool)) { echo "String: $a_bool"; } ?> ~~~ Example #2 var_dump()函数的使用 ~~~ <?php $a = array(1, 2, array("a", "b", "c")); var_dump($a); $b = 3.1; $c = true; var_dump($b, $c); ?> ~~~ 自己在浏览器中查看运行结果吧,运行方法在快速入门中讲过,以后不赘述。 当然我们有需要的时候,可以强制地将变量的数据类型进行[强制类型转换](http://php.net/manual/en/language.types.type-juggling.php#language.types.typecasting),或者使用[settype()](http://php.net/manual/en/function.settype.php)函数进行设置。 Example #3 强制类型转换 ~~~ <?php $foo = 10; // $foo is an integer $bar = (boolean) $foo; // $bar is a boolean ?> ~~~ Example #4 使用settype()函数设置变量的类型 ~~~ <?php $foo = "5bar"; // string $bar = true; // boolean settype($foo, "integer"); // $foo is now 5 (integer) settype($bar, "string"); // $bar is now "1" (string) ?> ~~~