本文目录导读:

- 函数参数类型提示
- 返回值类型提示
- 类/接口类型提示
- 属性类型提示 (PHP 7.4+)
- 联合类型 (PHP 8.0+)
- 伪类型和特殊类型
- 空置类型和可选参数
- 泛型风格 (通过PHPDoc,非严格运行时检查)
- 严格模式
- 实际示例
在 PHP 中,类型提示(Type Hinting)用于强制函数参数、返回值或类属性的类型,以下是详细的添加方法:
函数参数类型提示
基本类型(PHP 7.0+)
function greet(string $name, int $age): string {
return "Hello, $name! You are $age years old.";
}
echo greet("John", 25); // 正确
// greet(123, 25); // 错误:参数1必须是字符串
支持的类型
function example(
bool $flag, // 布尔值
int $number, // 整数
float $price, // 浮点数
string $text, // 字符串
array $items, // 数组
callable $callback, // 可调用
iterable $data, // 可迭代(7.1+)
object $obj, // 对象
mixed $anything // 任意类型(8.0+)
): void {
// 函数体
}
返回值类型提示
// 返回整数
function add(int $a, int $b): int {
return $a + $b;
}
// 返回数组
function getUsers(): array {
return ['John', 'Jane'];
}
// 返回空
function logMessage(string $msg): void {
echo $msg;
}
// 返回联合类型 (PHP 8.0+)
function getValue(bool $flag): int|string {
return $flag ? 42 : "default";
}
// 可空类型
function findUser(int $id): ?User {
// 返回User对象或null
}
类/接口类型提示
类的类型提示
class Car {}
class User {}
function drive(Car $vehicle): void {
echo "Driving a car";
}
// 必须传入Car类的实例
drive(new Car()); // 正确
// drive(new User()); // 错误:类型不匹配
接口类型提示
interface Logger {
public function log(string $message): void;
}
class FileLogger implements Logger {
public function log(string $message): void {
file_put_contents('log.txt', $message);
}
}
function processData(Logger $logger): void {
$logger->log("Processing data");
}
processData(new FileLogger()); // 正确
属性类型提示 (PHP 7.4+)
class User {
public string $name;
public int $age;
private ?string $email = null; // 可空类型
// 构造方法中的提升属性 (PHP 8.0+)
public function __construct(
public string $username,
public readonly int $createdAt,
private array $roles = []
) {}
}
$user = new User("John", time());
$user->name = "John"; // 正确
// $user->name = 123; // 错误:必须是字符串
联合类型 (PHP 8.0+)
function processInput(int|string $input): void {
if (is_int($input)) {
echo "处理整数:$input";
} else {
echo "处理字符串:$input";
}
}
// 合法调用
processInput(42);
processInput("hello");
伪类型和特殊类型
// mixed - 任何类型 (8.0+)
function debug(mixed $data): void {
var_dump($data);
}
// never - 不会返回 (8.1+)
function redirect(string $url): never {
header("Location: $url");
exit;
}
// true/false (8.2+)
function isAdult(int $age): true {
if ($age < 18) {
throw new Exception("Not adult");
}
return true;
}
空置类型和可选参数
// ? 表示可为null
function findUser(?int $id): ?User {
if ($id === null) {
return null;
}
// 查找用户...
}
// 默认值为null
function login(string $username, ?string $password = null): bool {
if ($password === null) {
return false;
}
// 验证...
}
泛型风格 (通过PHPDoc,非严格运行时检查)
/**
* @template T
* @param array<T> $items
* @return T|null
*/
function first(array $items): mixed {
return !empty($items) ? $items[0] : null;
}
$numbers = [1, 2, 3];
$first = first($numbers); // 类型推断为int|null
严格模式
declare(strict_types=1); // 文件顶部
function add(int $a, int $b): int {
return $a + $b;
}
add(5, 10); // 正确
// add("5", "10"); // 错误:会抛出TypeError
实际示例
class Product {
public function __construct(
public readonly int $id,
public string $name,
public float $price,
public array $tags = []
) {}
}
class Order {
private array $items = [];
public function addItem(
Product $product,
int $quantity = 1
): void {
$this->items[] = [
'product' => $product,
'quantity' => $quantity
];
}
/**
* @return array<int, array{product: Product, quantity: int}>
*/
public function getItems(): array {
return $this->items;
}
}
类型提示提高了代码的可读性和可靠性,建议在新项目中尽可能使用。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播