PHP 8中SplFixedArray改为IteratorAggregate后的代码适配求助
适配PHP8的修改方案
要让你的AbstractCollectionMutator类适配PHP8中SplFixedArray的接口变更,需要做以下关键修改:
修改后的完整代码
<?php declare(strict_types=1); namespace BitWasp\Bitcoin\Transaction\Mutator; abstract class AbstractCollectionMutator implements \IteratorAggregate, \ArrayAccess, \Countable { /** * @var \SplFixedArray */ protected $set; /** * @return array */ public function all(): array { return $this->set->toArray(); } /** * @return bool */ public function isNull(): bool { return count($this->set) === 0; } /** * @return int */ public function count(): int { return $this->set->count(); } /** * @return \Iterator */ public function getIterator(): \Iterator { return $this->set->getIterator(); } /** * @param int $offset * @return bool */ public function offsetExists($offset) { return $this->set->offsetExists($offset); } /** * @param int $offset */ public function offsetUnset($offset) { if (!$this->offsetExists($offset)) { throw new \InvalidArgumentException('Offset does not exist'); } $this->set->offsetUnset($offset); } /** * @param int $offset * @return mixed */ public function offsetGet($offset) { if (!$this->set->offsetExists($offset)) { throw new \OutOfRangeException('Nothing found at this offset'); } return $this->set->offsetGet($offset); } /** * @param int $offset * @param mixed $value */ public function offsetSet($offset, $value) { $this->set->offsetSet($offset, $value); } }
关键修改点说明
- 接口替换:将类实现的
\Iterator接口替换为\IteratorAggregate,匹配PHP8中SplFixedArray的接口变更。 - 移除冗余方法:删除原
\Iterator接口要求的rewind()、current()、key()、next()、valid()五个方法——现在无需手动代理迭代逻辑,转而通过IteratorAggregate规范获取迭代器。 - 添加核心方法:实现
IteratorAggregate接口要求的getIterator()方法,返回SplFixedArray内部的迭代器实例,PHP的迭代机制即可正常遍历集合类。 - 类型声明优化:给
getIterator()添加返回类型\Iterator,符合严格类型规范,提升代码可读性。
内容的提问来源于stack exchange,提问作者Kidd Kidd
相关产品推荐
相关产品推荐

