类型声明 #
一、类型声明概述 #
1.1 什么是类型声明 #
类型声明(Type Declarations)用于指定函数参数和返回值的类型:
php
<?php
function add(int $a, int $b): int
{
return $a + $b;
}
1.2 严格模式 #
默认为弱类型模式,开启严格模式后类型必须完全匹配:
php
<?php
declare(strict_types=1);
function add(int $a, int $b): int
{
return $a + $b;
}
add(1, 2);
add("1", "2");
二、参数类型声明 #
2.1 标量类型 #
php
<?php
function process(
int $integer,
float $float,
string $string,
bool $boolean
): void {
var_dump($integer, $float, $string, $boolean);
}
process(42, 3.14, "hello", true);
2.2 复合类型 #
php
<?php
function processArray(array $data): void
{
print_r($data);
}
function processObject(object $obj): void
{
var_dump($obj);
}
function processCallable(callable $fn): void
{
$fn();
}
2.3 类类型 #
php
<?php
class User {}
function greet(User $user): string
{
return "Hello!";
}
$user = new User();
greet($user);
2.4 接口类型 #
php
<?php
interface LoggerInterface
{
public function log(string $message): void;
}
function setLogger(LoggerInterface $logger): void
{
$this->logger = $logger;
}
2.5 self和parent #
php
<?php
class ParentClass {}
class ChildClass extends ParentClass
{
public function create(): self
{
return new self();
}
public function getParent(): parent
{
return new ParentClass();
}
}
三、返回值类型声明 #
3.1 基本类型 #
php
<?php
function getInt(): int
{
return 42;
}
function getFloat(): float
{
return 3.14;
}
function getString(): string
{
return "Hello";
}
function getBool(): bool
{
return true;
}
function getArray(): array
{
return [1, 2, 3];
}
3.2 void返回类型 #
php
<?php
function logMessage(string $message): void
{
echo $message;
}
function setConfig(array $config): void
{
$this->config = $config;
}
3.3 never返回类型(PHP 8.1+) #
php
<?php
function redirect(string $url): never
{
header("Location: $url");
exit;
}
function throwError(string $message): never
{
throw new Exception($message);
}
function infiniteLoop(): never
{
while (true) {
}
}
四、可空类型 #
4.1 基本语法 #
php
<?php
function findUser(int $id): ?User
{
if ($id <= 0) {
return null;
}
return new User($id);
}
function process(?string $value): string
{
return $value ?? "default";
}
4.2 与默认值null #
php
<?php
function greet(?string $name = null): string
{
return "Hello, " . ($name ?? "Guest");
}
greet();
greet(null);
greet("John");
4.3 可空参数vs可空返回 #
php
<?php
function process(?string $input): ?string
{
if ($input === null) {
return null;
}
return strtoupper($input);
}
五、联合类型(PHP 8.0+) #
5.1 基本语法 #
php
<?php
function process(int|float $number): string
{
return "Number: $number";
}
echo process(42);
echo process(3.14);
5.2 多类型联合 #
php
<?php
function format(string|int|float $value): string
{
return (string) $value;
}
function process(array|Collection $items): int
{
return count($items);
}
5.3 类类型联合 #
php
<?php
class PdfExporter {}
class CsvExporter {}
function export(PdfExporter|CsvExporter $exporter): string
{
return $exporter->export();
}
5.4 与可空类型结合 #
php
<?php
function process(int|string|null $value): string
{
return (string) $value;
}
function process(?int $value): ?string
{
return $value === null ? null : (string) $value;
}
六、交叉类型(PHP 8.1+) #
6.1 基本语法 #
php
<?php
interface Serializable
{
public function serialize(): string;
}
interface Jsonable
{
public function toJson(): string;
}
function process(Serializable&Jsonable $object): void
{
echo $object->serialize();
echo $object->toJson();
}
6.2 实际应用 #
php
<?php
interface HasId
{
public function getId(): int;
}
interface HasName
{
public function getName(): string;
}
function display(HasId&HasName $entity): void
{
echo "ID: {$entity->getId()}, Name: {$entity->getName()}";
}
七、混合类型(PHP 8.0+) #
7.1 mixed类型 #
php
<?php
function process(mixed $value): mixed
{
return $value;
}
process(42);
process("hello");
process([1, 2, 3]);
process(new stdClass());
process(null);
7.2 mixed等价于 #
php
<?php
function process(
array|bool|callable|int|float|null|object|resource|string $value
): void {}
八、类型声明进阶 #
8.1 静态返回类型 #
php
<?php
class Entity
{
public static function create(): static
{
return new static();
}
}
class User extends Entity {}
$user = User::create();
8.2 iterable类型 #
php
<?php
function process(iterable $items): void
{
foreach ($items as $item) {
echo $item;
}
}
process([1, 2, 3]);
process(new ArrayIterator([1, 2, 3]));
8.3 callable类型 #
php
<?php
function execute(callable $fn, mixed ...$args): mixed
{
return $fn(...$args);
}
echo execute('strtoupper', 'hello');
echo execute(fn($n) => $n * 2, 5);
九、类型检查 #
9.1 弱类型模式 #
php
<?php
function add(int $a, int $b): int
{
return $a + $b;
}
echo add("1", "2");
echo add(1.5, 2.5);
9.2 严格模式 #
php
<?php
declare(strict_types=1);
function add(int $a, int $b): int
{
return $a + $b;
}
echo add(1, 2);
echo add("1", "2");
9.3 类型转换 #
php
<?php
function process(int $value): int
{
return $value;
}
echo process("42");
echo process(42.9);
echo process(true);
十、实际应用 #
10.1 服务类 #
php
<?php
class UserService
{
public function __construct(
private UserRepository $repository,
private LoggerInterface $logger
) {}
public function find(int $id): ?User
{
$this->logger->log("Finding user: $id");
return $this->repository->find($id);
}
public function create(array $data): User
{
return $this->repository->create($data);
}
}
10.2 工厂模式 #
php
<?php
interface LoggerInterface {}
class FileLogger implements LoggerInterface {}
class DatabaseLogger implements LoggerInterface {}
class LoggerFactory
{
public function create(string $type): LoggerInterface
{
return match($type) {
'file' => new FileLogger(),
'database' => new DatabaseLogger(),
default => throw new InvalidArgumentException("Unknown type: $type")
};
}
}
10.3 数据传输对象 #
php
<?php
class UserDTO
{
public function __construct(
public readonly int $id,
public readonly string $name,
public readonly string $email,
public readonly ?string $phone = null
) {}
}
function createUser(UserDTO $data): User
{
return new User($data->name, $data->email);
}
十一、最佳实践 #
11.1 始终使用类型声明 #
php
<?php
declare(strict_types=1);
function process(string $input): string
{
return trim($input);
}
11.2 使用具体类型而非mixed #
php
<?php
function process(array $data): array
{
return $data;
}
function process(mixed $data): mixed
{
return $data;
}
11.3 使用接口类型 #
php
<?php
function save(LoggerInterface $logger): void
{
$logger->log("Saved");
}
11.4 合理使用可空类型 #
php
<?php
function find(int $id): ?User
{
return $this->repository->find($id);
}
function get(int $id): User
{
return $this->repository->findOrFail($id);
}
十二、总结 #
本章学习了:
- 参数类型声明
- 返回值类型声明
- 可空类型
- 联合类型
- 交叉类型
- 混合类型
- 严格模式
- 最佳实践
下一章将学习PHP数组。
最后更新:2026-03-26