PHP 类型转换
有时您需要将一个变量从一种数据类型更改为另一种数据类型,有时您希望变量具有特定的数据类型。 这可以通过类型转换来完成。
更改数据类型
在 PHP 中进行类型转换可以使用以下语句:
(string)
- 转换为字符串类型(int)
- 转换为整数类型(float)
- 转换为浮点类型(bool)
- 转换为布尔类型(array)
- 转换为数组类型(object)
- 转换为对象类型(unset)
- 转换为 NULL 类型
转换为字符串
要转换为字符串,请使用 (string)
语句:
实例
$a = 5; // 整数 $b = 5.34; // 浮点数 $c = "hello"; // 字符串 $d = true; // 布尔值 $e = NULL; // NULL $a = (string) $a; $b = (string) $b; $c = (string) $c; $d = (string) $d; $e = (string) $e; // 要验证 PHP 中任何对象的类型,请使用 var_dump() 函数: var_dump($a); var_dump($b); var_dump($c); var_dump($d); var_dump($e);
转换为整数
要转换为整数,请使用 (int)
语句:
实例
$a = 5; // 整数 $b = 5.34; // 浮点数 $c = "25 kilometers"; // 字符串 $d = "kilometers 25"; // 字符串 $e = "hello"; // 字符串 $f = true; // 布尔值 $g = NULL; // NULL $a = (int) $a; $b = (int) $b; $c = (int) $c; $d = (int) $d; $e = (int) $e; $f = (int) $f; $g = (int) $g;
转换为浮点数
要转换为浮点数,请使用 (float)
语句:
实例
$a = 5; // 整数 $b = 5.34; // 浮点数 $c = "25 kilometers"; // 字符串 $d = "kilometers 25"; // 字符串 $e = "hello"; // 字符串 $f = true; // 布尔值 $g = NULL; // NULL $a = (float) $a; $b = (float) $b; $c = (float) $c; $d = (float) $d; $e = (float) $e; $f = (float) $f; $g = (float) $g;
转换为布尔值
要转换为布尔值,请使用 (bool)
语句:
实例
$a = 5; // 整数 $b = 5.34; // 浮点数 $c = 0; // 整数 $d = -1; // 整数 $e = 0.1; // 浮点数 $f = "hello"; // 字符串 $g = ""; // 字符串 $h = true; // 布尔值 $i = NULL; // NULL $a = (bool) $a; $b = (bool) $b; $c = (bool) $c; $d = (bool) $d; $e = (bool) $e; $f = (bool) $f; $g = (bool) $g; $h = (bool) $h; $i = (bool) $i;
如果值为 0、NULL、false 或为空,则 (bool) 会将其转换为 false,否则为 true。
甚至 -1 也会转换为 true。
转换为数组
要转换为数组,请使用 (array)
语句:
实例
$a = 5; // 整数 $b = 5.34; // 浮点数 $c = "hello"; // 字符串 $d = true; // 布尔值 $e = NULL; // NULL $a = (array) $a; $b = (array) $b; $c = (array) $c; $d = (array) $d; $e = (array) $e;
转换为数组时,大多数数据类型都会转换为一个仅包含一个元素的索引数组。
NULL 值会转换为一个空的数组对象。
对象会转换为关联数组,其中属性名称成为键,属性值成为值:
实例
将对象转换为数组:
class Car { public $color; public $model; public function __construct($color, $model) { $this->color = $color; $this->model = $model; } public function message() { return "My car is a " . $this->color . " " . $this->model . "!"; } } $myCar = new Car("red", "Volvo"); $myCar = (array) $myCar; var_dump($myCar);
转换为对象
要转换为对象,请使用 (object)
语句:
实例
$a = 5; // 整数 $b = 5.34; // 浮点数 $c = "hello"; // 字符串 $d = true; // 布尔值 $e = NULL; // NULL $a = (object) $a; $b = (object) $b; $c = (object) $c; $d = (object) $d; $e = (object) $e;
转换为对象时,大多数数据类型都会转换为一个仅包含一个名为 "scalar" 的属性和相应值的对象。
NULL 值会转换为一个空对象。
索引数组会转换为对象,其中索引号作为属性名称,值作为属性值。
关联数组会转换为对象,其中键作为属性名称,值作为属性值。
实例
将数组转换为对象:
$a = array("Volvo", "BMW", "Audi"); // 索引数组 $b = array("Bill"=>"35", "Steve"=>"37", "Elon"=>"43"); // 关联数组 $a = (object) $a; $b = (object) $b;
转换为 NULL
要转换为 NULL,请使用 (unset)
语句:
实例
$a = 5; // 整数 $b = 5.34; // 浮点数 $c = "hello"; // 字符串 $d = true; // 布尔值 $e = NULL; // NULL $a = (unset) $a; $b = (unset) $b; $c = (unset) $c; $d = (unset) $d; $e = (unset) $e;