关于是否要在 php 8 中引入 union types 的投票已于近日结束,投票结果显示有 61 名 php 开发组成员投了赞成票,5 名投了反对票。
还留意到鸟哥在投票中投了反对票~
因此根据投票结果,官方已确认将会在 php 8 中引入 union types 2.0。
关于 union types 的具体讨论可在 github 查看,下面我们来简单了解一下 union types(联合类型)。
根据官方的介绍,union types(联合类型)支持接收多个不同类型的值,而不仅仅是单一类型。php 目前已经支持两种特殊的联合类型:
·type or null,使用特殊的type语法
·array or traversable,使特殊的iterable类型
不过 php 目前尚不支持任意的联合类型。如要使用,需通过 phpdoc 注释的帮助,示例如下:
<pre style="margin: 0px; padding: 0px; font-family: "courier new" !important; font-size: 14px; line-height: 1.5em; white-space: pre-wrap; overflow-wrap: break-word;">class number { /*** @var int|float number; /*** @param int|float number) { number;} /*** @return int|float */public function getnumber () { return $this->number;}}</pre>
根据数据统计的结果,在开源生态以及 php 自身的标准库中使用联合类型非常普遍。官方表示,如果 php 能支持联合类型,将会允许我们将更多类型信息从 phpdoc 迁移至函数签名,这具有以下常见的优点:
·类型实际上是强制执行的,因此可以及早发现错误。
·因为它们是强制性的,所以类型信息不太可能变得过时或遗漏边缘情况。
·在继承过程中会检查类型,以执行里氏替换原则(liskov substitution principle)
·可通过反射获得类型信息。
·语法比 phpdoc 简洁。
泛型之后,联合类型可以说是目前类型声明系统中最大的“缺口”。
****提案****
联合类型使用 t1t2… 语法,可在所有接受的类型中使用:
<pre style="margin: 0px; padding: 0px; font-family: "courier new" !important; font-size: 14px; line-height: 1.5em; white-space: pre-wrap; overflow-wrap: break-word;">class number { private int|float number): void { number;} public function getnumber (): int|float { return $this->number;}}</pre>
支持的类型
联合类型支持 php 当前支持的所有类型:空类型、可空联合类型、false pseudo-type、重复和冗余类型。
****类型语法****
除特殊void类型外,php 的类型语法现在可以通过以下语法来描述:
<pre style="margin: 0px; padding: 0px; font-family: "courier new" !important; font-size: 14px; line-height: 1.5em; white-space: pre-wrap; overflow-wrap: break-word;">type: simple_type | "?" simple_type | union_type;union_type: simple_type "|" simple_type | union_type "|" simple_type;simple_type: "false" # only legal in unions| "null" # only legal in unions| "bool"| "int"| "float"| "string"| "array"| "object"| "iterable"| "callable" # not legal in property types| "self"| "parent"| namespaced_name;</pre>10
,大量的免费php入门教程,欢迎在线学习!