虽然 PHP 是一门弱类型的语言,但个人觉得类型还是有必要存在的,有时我们就会需要对变量进行类型转换。
在 PHP 中有两种方式让你进行类型转换:强制类型转换和 settype() 函数类型转换。
1. 强制类型转换:
可强制转换的类型
(boolean) | 强转成 boolean 类型 |
(integer) | 强转成整型 |
(float) | 强转成浮点型 |
(string) | 强转成字符串型 |
(array) | 强转成数组类型 |
(object) | 强转成对象 |
强制转换其实很简单,只需在变量名前加上小括号,小括号中包含要强制转换成的类型即可,例:
// 定义变量 $num
$num = 123;
// 将变量 $num 强制转换为 string 类型并赋值给变量 $str
$str = (string)$num;
参考 PHP 官方文档,我们知道 settype() 函数的语法如下:
bool settype ( mixed &$var , string $type )
其中,var 为要进行类型转换的变量, type 为要转换成的类型;
type 的可选值有:
"boolean" (或为"bool",从 PHP 4.2.0 起)
"integer" (或为"int",从 PHP 4.2.0 起)
"float" (只在 PHP 4.2.0 之后可以使用,对于旧版本中使用的"double"现已停用)
"string"
"array"
"object"
"null" (从 PHP 4.2.0 起)
转换成功时返回 TRUE
, 失败则返回 FALSE;
示例:
<?php
// $foo 目前是 string 类型
$foo = "3bar";
// $bar 目前是 boolean 类型
$bar = true;
echo '转换前的 $foo:' . $foo . "</br>";
echo '转换前的 $bar:' . $bar . "</br>";
// $foo 现在是 3 (integer)
settype($foo, "integer");
// $bar 现在是 "1" (string)
settype($bar, "string");
echo '转换后的 $foo:' . $foo . "</br>";
echo '转换后的 $bar:' . $bar . "</br>";
?>
运行结果:
转换前的 $foo:3bar
转换前的 $bar:1
转换后的 $foo:3
转换后的 $bar:1