PHP函数参数与返回值类型PHP从7开始逐步完善了类型系统。函数参数和返回值可以声明类型。今天说说各种类型声明的用法。基本类型声明。phpdeclare(strict_types1);function process(int $id, string $name, float $price, bool $active): array{return compact(id, name, price, active);}print_r(process(1, 商品, 99.99, true));?可空类型用?表示。phpfunction findUser(int $id): ?array{$users [1 [name 张三]];return $users[$id] ?? null;}$user findUser(1);echo $user[name] . \n;$user findUser(999);var_dump($user);?联合类型用|分隔。phpfunction formatValue(int|string|float $value): string{return match (true) {is_int($value) 整数: . number_format($value),is_float($value) 浮点数: . number_format($value, 2),is_string($value) 字符串: . $value,};}echo formatValue(42) . \n;echo formatValue(3.14) . \n;echo formatValue(hello) . \n;?void类型表示没有返回值。phpfunction log(string $message): void{file_put_contents(/tmp/app.log, $message . \n, FILE_APPEND);}log(用户登录);?never类型表示函数不会返回。phpfunction abort(string $message): never{throw new RuntimeException($message);}function redirect(string $url): never{header(Location: $url);exit;}?mixed类型表示任意类型。phpfunction debug(mixed $value): void{var_dump($value);}debug(42);debug(hello);debug([1, 2, 3]);?iterable类型表示可遍历。phpfunction processItems(iterable $items): void{foreach ($items as $item) {echo $item . \n;}}processItems([1, 2, 3]);processItems(new ArrayIterator([4, 5, 6]));?类型声明让函数的接口更清晰。调用者知道传什么参数、得到什么返回值。开启strict_types后类型不匹配会直接报错避免隐式转换导致的bug。