Categories
PHP

PHP 8 新特性:联合类型

定义

在 PHP 8 中,定义函数参数的类型时,可以指定多种类型;也就是允许它的值为这些类型中的一种;我们称这种类型为联合类型(Union Types)。

一般语法

联合类型的语法格式为:

Type1|Type2|Type3|...

举第一个例子 🌰:

<?php
function printScore(int|float $score) {
    printf("score: %s\n", $score);
}
printScore(90);
printScore(85.6);
printScore("zhang");

上文中 int|float 指明了参数 $score 为联合类型,它可以是 int 类型 或 float 类型。

输出结果为:

score: 90
score: 85.6
PHP Fatal error: Uncaught TypeError: printScore(): Argument #1 ($score) must be of type int|float, string given.

上文中,因为传递了不允许的类型 string,直接抛出 TypeError 类型的错误

?Type 语法

我们可以指定类型为某个 Class 或者 null,比如 DateTime|null,简化写法为 ?Type。

另外,不支持单独使用类型 null。

举第二个例子 🌰:

<?php
function showTime(?DateTime $time) {
    if (is_null($time)) {
        printf("Time: Null\n");
    } else {
        printf("Time: %s\n", $time->format(DateTimeInterface::ISO8601));
    }
}
showTime(new DateTime());
showTime(null);

输出为:

Time: 2020-12-04T16:32:33+0000
Time: Null

伪类型 false

可以在联合类型使用伪类型 false,比如 string|false。另外,不支持单独使用类型 false。暂不支持伪类型 true(保留关键字)。

参考资料

扫码阅读和分享

Leave a Reply

Your email address will not be published. Required fields are marked *