在这段代码中
<?php declare(strict_types=1);
namespace Persist;
trait IteratorTrait {
/* #region Iterator */
/** @var bool $valid true if a valid object */
private bool $valid = false;
public function current ( ): object { return $this; }
public function key ( ): mixed { return $this-> {$this->getPrimaryKey()} ; }
public function valid ( ): bool { return $this-> valid; }
public function next ( ): void { $this-> findNext(); }
public function rewind ( ): void { $this-> findFirst(); }
/* #endregion */
};
Run Code Online (Sandbox Code Playgroud)
我在使用该特征的类中收到错误(在 php 7.5 上):AH01071: Got error 'PHP message: PHP Fatal error: Uncaught TypeError: Return value of NameSpace\\test::key() must be an instance of mixed, int returned in...
如果删除 :mixed 键,我会在 PHP 8.1 上收到错误:PHP Deprecated: Return type of NameSpace\test::key() should either be compatible with Iterator::key(): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in ...
我在这里读到的内容让我感到困惑。
如果我把这个添加到我得到的特质中Fatal error: Attribute "ReturnTypeWillChange" cannot target property (allowed targets: method) in IteratorTrait.php on line 10
编辑:发生此错误是因为在 key() 方法之前定义了一个属性。
我应该在哪里更改才能使其在 7.x 和 8.x 上运行?
需要#[\ReturnTypeWillChange]直接出现在返回混合的方法之前,但需要省略混合才能使其在两个 PHP 版本中都起作用。正确的语法是:
<?php declare(strict_types=1);
namespace Persist;
trait IteratorTrait {
/* #region Iterator */
/** @var bool $valid true if a valid object */
private bool $valid = false;
public function current ( ): object { return $this; }
#[\ReturnTypeWillChange]
public function key ( ) { return $this-> {$this->getPrimaryKey()} ; }
public function valid ( ): bool { return $this-> valid; }
public function next ( ): void { $this-> findNext(); }
public function rewind ( ): void { $this-> findFirst(); }
/* #endregion */
};
Run Code Online (Sandbox Code Playgroud)
在 PHP 8.1.5 和 7.4.29 上测试。
| 归档时间: |
|
| 查看次数: |
2089 次 |
| 最近记录: |