xp-lang / xp-records
PHP 的 XP 记录
v3.1.0
2024-09-07 09:04 UTC
Requires
- php: >=7.4.0
- xp-framework/compiler: ^9.0 | ^8.0 | ^7.0
- xp-framework/core: ^12.0 | ^11.0 | ^10.0
Requires (Dev)
- xp-framework/test: ^2.0 | ^1.0
README
为 XP 编译器 提供的插件,它向 PHP 语言添加了 record
语法。记录声明一个具有不可变组件的最终类,并为每个成员提供适当的访问器和构造函数,该构造函数实现了 lang.Value
接口。
示例
// Declaration namespace com\example; use IteratorAggregate, Traversable; record Range(int $lo, int $hi) implements IteratorAggregate { public function getIterator(): Traversable { for ($i= $this->lo; $i <= $this->hi; $i++) { yield $i; } } } // Usage $r= new Range(1, 10); $r->lo(); // 1 $r->hi(); // 10 $r->toString(); // "com.example.Range(lo: 1, hi: 10)" foreach ($r as $item) { // 1, 2, 3, ... 10 }
注意:生成的 toString()
、hashCode()
和 compareTo()
方法可能会在记录体中提供实现而被覆盖。
初始化
为了验证构造函数参数,添加如下初始化块
use lang\IllegalArgumentException; record Range(int $lo, int $hi) { init { if ($this->lo > $this->hi) { throw new IllegalArgumentException('Lower border may not exceed upper border'); } } }
此块在成员从构造函数参数初始化后调用。
解构
要将记录解构为其成员,使用调用语法
// Using the declaration from above: $r= new Range(1, 10); // Use https://wiki.php.net/rfc/short_list_syntax (>= PHP 7.1) [$lo, $hi]= $r(); // Optionally map the members, returns the string "1..10" $string= $r(fn($lo, $hi) => "{$lo}..{$hi}");
安装
在将 XP 编译器安装到您的项目后,也包含此插件。
$ composer require xp-framework/compiler # ... $ composer require xp-lang/xp-records # ...
不需要进行其他操作。