LoginSignup
0
0

More than 1 year has passed since last update.

PHP的(PHPStan)ジェネリクス型

Last updated at Posted at 2022-09-06

PHPStanを使うとPHPでもジェネリクス型が使える

なのでこんな感じで書いてみたら...

<?php

interface Animal{
    /**
     * @template E of Food
     * @param E $food
     * @return void
     */
    public function eat($food): void;
}

interface Food {}

class Cat implements Animal {
    
    /**
     * @param Fish $fish
     * @return void
     */
    public function eat(Fish $fish): void
    {
        //うまいうまい
    }
}

class Fish implements Food{
    
}

Catのeat()がインターフェースのものと互換性がないと怒られます。

原因は簡単で、PHPは型境界を理解してくれないから
なので、仮引数型の宣言をやめて、PHPDocにだけ書くようにする。

<?php

interface Animal{
    /**
     * @template E of Food
     * @param E $food
     * @return void
     */
    public function eat($food): void;
}

interface Food {}

class Cat implements Animal {
    
    /**
     * @param Fish $fish
     * @return void
     */
    public function eat($fish): void
    {
        //うまいうまい
    }
}

class Fish implements Food{
    
}

これでよし

0
0
2

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
0
0