ReturnTypeWillChange
PHP組み込みのアトリビュート。
バージョンアップに伴って型宣言が変更されたインターフェイスの警告を抑止できる
PHP 8.1で追加された
PHP RFC: Add return type declarations for internal methods
どのようなときに使うのか
たとえばCountableインターフェイスはPHP 8.1で型宣言が変更された
code:php
<?php
class MyCountable implements Countable
{
public function count()
{
return 1;
}
}
PHP 8.1以降では型宣言が追加されたため、以下のような警告が出る https://3v4l.org/l0JkQ/rfc#vgitmaster
Deprecated: Return type of MyCountable::count() should either be compatible with Countable::count(): int, or the #ReturnTypeWillChange attribute should be used to temporarily suppress the notice in /in/l0JkQ on line 5
このケースにおいてはPHP 7以降だけをサポートするなら型宣言を追加するのがよい
public function count(): int
しかしPHP 5では型宣言はできない
そのようなときに#[\ReturnTypeWillChange]アトリビュートを使うとPHP 8.1は警告を発生しない
code:php
class MyCountable implements Countable
{
#\ReturnTypeWillChange
public function count()
PHP 5やPHP 7ではアトリビュートはコメントアウトとして読み飛ばされるため互換性の問題は生じない
PHP 8.0であっても実際にアトリビュートを取得しない限りは未定義でも問題ない
同様にSessionInterfaceも問題がある
ユニオン型宣言はPHP 8.0が必要なのでPHP 7とPHP 8両対応にできない。
code:php
public gc(int $max_lifetime): int|false