深入探究特性(Attributes)、readonly、一等可调用值以及 PHP 8 严格类型的内部机理。
在 Kodokon 中打开本课特性(Attributes)用真正的、由引擎校验的类取代了 docblock 注解。一个特性不过是一份沉睡的元数据:写下 #[Route('/users')] 并不会创建任何对象。只有当某段代码通过反射查询它并调用 newInstance() 时,它才会苏醒过来 - 这正是框架在启动时构建路由表所做的事。它所允许的目标(TARGET_METHOD、TARGET_CLASS……)本身也是由特性类上的一个特性来声明的。
<?php
declare(strict_types=1);
#[Attribute(Attribute::TARGET_METHOD)]
final class Route
{
public function __construct(
public readonly string $path,
public readonly string $method = 'GET'
) {}
}
final class UserController
{
#[Route('/users', method: 'GET')]
public function index(): array
{
return ['users' => []];
}
}
$ref = new ReflectionMethod(
UserController::class,
'index'
);
foreach ($ref->getAttributes(Route::class) as $attr) {
$route = $attr->newInstance();
echo $route->method, ' ', $route->path, PHP_EOL;
}readonly - 8.1 中作用于属性,8.2 中作用于整个类 - 保证一个属性只被写入一次,而且只能在类的作用域内写入。它是构建值对象的利器:任何"修改"都变成了构造一个新对象,这消除了一整类共享状态的 bug。一个 readonly 类要求它的所有属性都带类型且非静态。
<?php
declare(strict_types=1);
final readonly class Money
{
public function __construct(
public int $amount,
public string $currency
) {}
public function add(Money $other): self
{
if ($other->currency !== $this->currency) {
throw new InvalidArgumentException(
'Currency mismatch'
);
}
return new self(
$this->amount + $other->amount,
$this->currency
);
}
}
$total = new Money(500, 'EUR');
$total = $total->add(new Money(250, 'EUR'));
echo $total->amount;一等可调用语法 strtoupper(...)(PHP 8.1)会从任意函数或方法创建一个 Closure。不同于 'strtoupper' 这样的字符串或 [$obj, 'method'] 这样的数组,这个符号会在创建时就被校验,静态分析工具也能从头到尾地追踪类型。对于实例方法,闭包会捕获对象;对于静态方法,则只捕获类。
<?php
declare(strict_types=1);
$words = ['php', 'rust', 'go'];
$upper = strtoupper(...);
var_dump($upper('php'));
print_r(array_map(strtoupper(...), $words));
final class Mailer
{
public function send(string $to): bool
{
return $to !== '';
}
public static function ping(): string
{
return 'pong';
}
}
$mailer = new Mailer();
$send = $mailer->send(...);
$ping = Mailer::ping(...);
var_dump($send('dev@example.org'), $ping());