LoginSignup
3
0

More than 1 year has passed since last update.

PHP8.1でDeprecatedの警告が出る件 #[\ReturnTypeWillChange]

Last updated at Posted at 2022-12-01

こういうやつ

Deprecated Error: Return type of Foo\Bar\Hoge\Hoge::jsonSerialize() should either be compatible with JsonSerializable::jsonSerialize(): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice
In [/var/www/html/api/vendor/Foo/Bar/src/Hoge/Hoge.php, line 179]

業務で使っているCakePHP4.1のレポジトリをPHP8.0からPHP8.1にしたタイミングで大量に発生した。

これは何なのかっていうのを調べると、PHPのマニュアルに行き着いた。

PHP のバージョン間の互換性を保ちたいがために、 戻り値の型を宣言できない場合、 アトリビュート #[ReturnTypeWillChange] を追加することで警告を抑止できます。

継承元のクラスと異なる戻り値が返る場合にこの警告が出る様子。

マニュアルのとおりに使っているメソッドに [\ReturnTypeWillChange] というアノテーションをつけてあげれば回避はできる。

アノテーションつける

/**
 * json_encodeされたらvalueを返す
 *
 * @return string|int getValue()の値
 */
#[\ReturnTypeWillChange]
public function jsonSerialize()
{
    return $this->getValue();
}

このサンプルは JsonSerializable を継承しているんだけど、 jsonSerialize メソッドの戻り値は mixed になっているのよね。
アノテーションをセットするのは適切な戻り値に設定できない場合の苦肉の策なのね。

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0