哈希空间 Ctrl + F 进行搜索
首页 php手册中文版 CSS中文手册 哈希文档 Markdown在线工具

PHP types 组件

类型转换

PHP 在变量声明时不需要定义类型。在这种情况下,变量的类型由存储的值决定。也就是说,如果 string 赋值给 $var,然后 $var 的类型就是 string。之后将 int 值赋值给 $var,它将是 int 类型。

PHP 可能会尝试在某些上下文中自动将值转换为另一种类型。不同的上下文有:

注意: 当值需要解释为不同类型时,值本身会改变类型。

强制将变量当做某种变量来求值,参见类型转换一节。要更改变量的类型,请参阅 settype() 函数。

Numeric contexts

This is the context when using an arithmetical operator.

在这种情况下,如果任一运算对象是 float(或者不能解释为 int),则两个运算对象都将解释为 float,结果也将是 float。否则,运算对象将解释为 int,结果也将是 int。自 PHP 8.0.0 起,如果无法解释其中一个运算对象,则会抛出 TypeError

String contexts

This is the context when using echo, print, string interpolation, or the string concatenation operator.

这种情况下,值将会解释为 string

Logical contexts

This is the context when using conditional statements, the ternary operator, or a logical operator.

在这种情况下,值将会解释为 bool

Integral and string contexts

This is the context when using a bitwise operators.

在这种情况下,如果所有的运算对象都是 string,则结果也将是 string。否则运算对象将解释为 int,结果也将是 int。如果其中一个运算对象无法解释,则会抛出 TypeError

Comparative contexts

This is the context when using a comparison operator.

在此上下文中发生的类型转换在比较多种类型中进行了说明。

Function contexts

This is the context when a value is passed to a typed parameter, property, or returned from a function which declares a return type.

在此上下文中,当激活(默认)强制类型模式时,只有标量值可以转为另外一个标量值。对于简单类型声明,行为如下所示:

如果类型声明是联合,查看有关强制类型与联合类型 的章节。
警告

自 PHP 8.1.0 起弃用内部函数自动将 null 转换为标量类型的行为。

类型转换

类型转换通过在值前面的括号中写入类型来将值转换指定的类型。

<?php
$foo 
10;   // $foo 是 int
$bar = (bool) $foo;   // $bar 是 bool
?>

允许的转换是:

注意:

(integer)(int) 转换的别名。(boolean)(bool) 转换的别名。(binary)(string) 转换的别名。(double)(real)(float) 转换的别名。这些转换不使用标准的类型名称,不推荐使用。

警告

自 PHP 8.0.0 起弃用 (real) 转换别名。

警告

自 PHP 7.2.0 起弃用 (unset) 转换。注意 (unset) 转换等同于将值 NULL 通过赋值或者调用给变量。自 PHP 8.0.0 起移除 unset 转换。

警告

向前兼容 (binary) 转换和 b 前缀转换。注意 (binary) 转换和 (string) 相同,但是这可能会改变且不应依赖。

注意:

在转换的括号内忽略空格。因此,以下两个转换是等价的:

<?php
$foo 
= (int) $bar;
$foo = ( int ) $bar;
?>

将文字 string 和变量转换为二进制 string

<?php
$binary 
= (binary) $string;
$binary b"binary string";
?>

注意: 除了将变量转换为 string 之外,还可以将变量放在双引号内。

<?php
$foo 
10;            // $foo 是 int
$str "$foo";        // $str 是 string
$fst = (string) $foo// $fst 也是 string

// 打印出 "they are the same"
if ($fst === $str) {
    echo 
"they are the same";
}
?>

有时在类型之间转换时确切地会发生什么可能不是很明显。更多信息见如下不分:

注意: 因为 PHP 的 string 支持使用与 array 索引相同的语法,通过偏移量进行索引,所以以下示例适用于所有 PHP 版本:

<?php
$a    
'car'// $a 是 string
$a[0] = 'b';   // $a 依然是 string
echo $a;       // bar
?>
请查看章节标题为存取和修改字符串中的字符获取更多信息。
打开 哈希空间 微信小程序中查看更佳