
上QQ阅读APP看书,第一时间看更新
4.9 PHP 8的新变化2——联合类型和mixed类型
1.联合类型
PHP 8开始支持联合类型,此时函数可以声明并接收多个不同类型的值,它是两种或多种类型的集合,使用时可以选择其一。例如:
<?php function getType(string|array|bool $a) { var_dump($a); //输出变量的类型 } getParam(false); getParam('苹果'); ?>
程序运行后输出内容如下:
bool(false) string(6) "苹果"
2.mixed类型
PHP 8开始支持mixed类型,该类型等价于:
array|bool|callable|int|float|null|object|resource|string
例如下面的代码:
<?php declare(strict_types=1); function debug_function(mixed ...$data) { var_dump($data); } debug_function(1, '黄金', []); exit; ?>
程序运行后输出内容如下:
?array(3) { [0]=> int(1) [1]=> string(6) "黄金" [2]=> array(0) { } }