Help us understand the problem. What is going on with this article?

PHPによるEnumの実装方法がついに決着した

ときどきPHPStanの更新を一応眺めているんだけど、PHPStan 0.12.20 でいつの間にか欲しかった機能が実装されていた。
@param に定数が使えるようになっていた。定数だけだと一見無意味だけれど、ワイルドカードやunionが使える。

これによって、今まで様々な実装があったEnumをどうするかという問題が解決した。
単にconstを集めたシンプルなクラスにすれば良い。

<?php
namespace App;
class Env
{
    public const DEVELOP = 'development';
    public const STAGING = 'staging';
    public const PRODUCTION = 'production';
}
<?php
namespace App;
class Main
{
    /**
     * @param Env::* $env
     */
    public static function doSomethingByEnv($env): void
    {
    }

    public static function main(): void
    {
        self::doSomethingByEnv('development');
        self::doSomethingByEnv(Env::DEVELOP);
        self::doSomethingByEnv('dev');
    }
}

PHPStan実行結果

zsh % php7.4 vendor/bin/phpstan analyse src        [~/prog/php/phpstan/sample1]
Note: Using configuration file /home/nishimura/prog/php/phpstan/sample1/phpstan.neon.dist.
 3/3 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%

 ------ ----------------------------------------------------------------- 
  Line   Main.php                                                         
 ------ ----------------------------------------------------------------- 
  16     Parameter #1 $env of static method App\Main::doSomethingByEnv()  
         expects 'development'|'production'|'staging', 'dev' given.       
 ------ ----------------------------------------------------------------- 


 [ERROR] Found 1 error                                                          

enum.png

PHPらしい手抜き加減がなかなか良い感じである。
unionにすれば単純なチェックボックスのフォームみたいな処理でも型チェックができそうだ。
たぶん @param int|float $id とかよりも @param 'GET'|'POST' $method とかの方が使い道がある。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした