触ってみた感想はenumと構造体が合わさった感じ。
メソッドを作れたり継承・traitも適用できるあたりはクラスとしての性格も持っている。
主な使いそうな箇所はこんな感じ
Platforms::Ios で定義したenumの値にアクセスする。
Platforms::Ios->name でenum自体の文字列’Ios’が取得できる。(toString()的な感じ)
Platforms::tryFrom(1) でマッチする値のenumを取得。ない場合はNullを返す。
Platforms::Ios->getType() のように独自の挙動をするメソッドをenumに定義できる。
Platforms::cases()ですべてのenumを列挙。
具体的な使用例はこんな感じなのではないかなと。
<?php
enum Platforms : int{
case Ios = 1;
case Android = 2;
case Windows = 3;
case Macintosh = 4;
public function getType(){
return match($this){
self::Ios, self::Android => 'Mobile',
self::Windows, self::Macintosh => 'PC',
};
}
}
function CheckPlatform(Platforms $platform){
echo '============== enum check start =============='.PHP_EOL;
var_dump($platform->value);
var_dump($platform->name);// like toString
var_dump($platform->getType());
echo '============== enum check end =============='.PHP_EOL;
}
$pf = Platforms::from(4);
CheckPlatform($pf);
// $pf = Platforms::from(9999);// Fatal error: Uncaught ValueError:
$pf = Platforms::tryFrom(9999) ?? Platforms::Ios;
CheckPlatform($pf);
var_dump(Platforms::cases());
/*
============== enum check start ==============
int(4)
string(9) "Macintosh"
string(2) "PC"
============== enum check end ==============
============== enum check start ==============
int(1)
string(3) "Ios"
string(6) "Mobile"
============== enum check end ==============
array(4) {
[0]=>
enum(Platforms::Ios)
[1]=>
enum(Platforms::Android)
[2]=>
enum(Platforms::Windows)
[3]=>
enum(Platforms::Macintosh)
}
*/
ほかにもinterfaceや継承、traitなどの例やobjectとの違いが公式ドキュメントで詳しく紹介されている。
https://www.php.net/manual/en/language.enumerations.overview.php