类型系统

PHP uses a nominal type system with a strong behavioral subtyping relation. The subtyping relation is checked at compile time whereas the verification of types is dynamically checked at run time.

PHP 的类型系统支持各种基础类型,可以组合在一起创建更加复杂的类型。其中一些类型可以写成类型声明

基本类型

一些基础类型是内置类型,跟语言紧密集成,不能用用户定义类型重现(reproduced)。

基础类型列表是:

  • 内置类型
    • null 类型
    • 标量类型:
      • bool 类型
      • int 类型
      • float 类型
      • string 类型
    • array 类型
    • object 类型
    • resource 类型
    • never 类型
    • void 类型
    • 相对类类型selfparentstatic
  • 字面量类型
    • false
    • true
  • 用户定义的类型(通常称为类类型)
  • callable 类型

复合类型

可以将简单类型组合为复合类型。PHP 允许使用以下方式组合类型:

  • 类类型(接口和类名)的交集。
  • 类型联合。

交集类型

交集类型接受满足多个类类型声明的值,而不是单个值。交集类型中的每个类型由 & 符号连接。因此,类型 TUV 组成的交集类型将写成 T&U&V

联合类型

联合类型接受多个不同类型的值,而不是单个类型。联合类型中的每个类型由 | 符号连接。因此类型 TUV 的联合类型写成 T|U|V。如果其中一种类型是交集类型,需要使用括号括起来,在 DNF 中写成:T|(X&Y)

类型别名

PHP 支持两种类型别名:mixediterable,分别对应 object|resource|array|string|float|int|bool|nullTraversable|array联合类型

注意: PHP 不支持用户定义类型别名。

add a note

User Contributed Notes

There are no user contributed notes for this page.
To Top