public function __construct(string $title, Status $status) { $this->title = $title; $this->status = $status; } } PHP 8.2 readonly class BlogData { public string $title;
public Status $status;
public function __construct(string $title, Status $status) { $this->title = $title; $this->status = $status; } } 析取范式 (DNF)类型 RFC 文档 PHP < 8.2 class Foo { public function bar(mixed $entity) { if ((($entity instanceof A) && ($entity instanceof B)) || ($entity === null)) { return $entity; }
throw new Exception('Invalid entity'); } } PHP 8.2 class Foo { public function bar((A&B)|null $entity) { return $entity; } } DNF 类型允许我们组合 union 和 intersection类型,遵循一个严格规则:组合并集和交集类型时,交集类型必须用括号进行分组。 允许 null、false 和 true 作为独立类型 RFC RFC PHP < 8.2 class Falsy { public function almostFalse(): bool { /* ... */ *}
public function almostTrue(): bool { /* ... */ *}
public function almostNull(): string|null { /* ... */ *} } PHP 8.2 class Falsy { public function alwaysFalse(): false { /* ... */ *}
public function alwaysTrue(): true { /* ... */ *}
public function alwaysNull(): null { /* ... */ *} } 新的“随机”扩展 RFC RFC 文档 PHP 8.2 use Random\Engine\Xoshiro256StarStar; use Random\Randomizer;
$blueprintRng = new Xoshiro256StarStar( hash('sha256', "Example seed that is converted to a 256 Bit string via SHA-256", true) );
$fibers = []; for ($i = 0; $i < 8; $i++) { $fiberRng = clone $blueprintRng; // Xoshiro256**'s 'jump()' method moves the blueprint ahead 2**128 steps, as if calling // 'generate()' 2**128 times, giving the Fiber 2**128 unique values without needing to reseed. $blueprintRng->jump();
$fibers[] = new Fiber(function () use ($fiberRng, $i): void { $randomizer = new Randomizer($fiberRng);
// The randomizer will use a CSPRNG by default. $randomizer = new Randomizer();
// Even though the fibers execute in a random order, they will print the same value // each time, because each has its own unique instance of the RNG. $fibers = $randomizer->shuffleArray($fibers); foreach ($fibers as $fiber) { $fiber->start(); } “随机”扩展为随机数生成提供了一个新的面向对象的 API。这个面向对象的 API 提供了几个类(“引擎”),提供对现代算法的访问,这些算法在对象中存储其状态,以允许多个独立的可播种序列,而不是依赖于使用 Mersenne Twister 算法的全局种子随机数发生器(RNG)。
@晨曦,你自己试试呗,我觉得唯一的问题可能是部分类需要添加
#[\AllowDynamicProperties]