Created
March 7, 2013 16:27
-
-
Save hirak/5109317 to your computer and use it in GitHub Desktop.
PHPで列挙型(enum)を作る ref: http://qiita.com/items/71e385b56dcaa37629fe
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
abstract class Enum | |
{ | |
private $scalar; | |
function __construct($value) | |
{ | |
$ref = new ReflectionObject($this); | |
$consts = $ref->getConstants(); | |
if (! in_array($value, $consts, true)) { | |
throw new InvalidArgumentException; | |
} | |
$this->scalar = $value; | |
} | |
final static function __callStatic($label, $args) | |
{ | |
$class = get_called_class(); | |
$const = constant("$class::$label"); | |
return new $class($const); | |
} | |
//元の値を取り出すメソッド。 | |
//メソッド名は好みのものに変更どうぞ | |
final function valueOf() | |
{ | |
return $this->scalar; | |
} | |
final function __toString() | |
{ | |
return (string)$this->scalar; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function doSomething(Suit $suit) { | |
//Suitというタイプヒントによって、 | |
//$suitは必ず4種類のうちのどれかだと保証されている | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// トランプのスート型を定義する。4種類しか値を取らない。 | |
// Enumをextendして、定数をセット | |
final class Suit extends Enum | |
{ | |
const SPADE = 'spade'; | |
const HEART = 'heart'; | |
const CLUB = 'club'; | |
const DIAMOND = 'diamond'; | |
} | |
//インスタンス化 | |
$suit = new Suit(Suit::SPADE); | |
echo $suit; //toString実装済みなので文字列キャスト可能 | |
echo $suit->valueOf(); //生の値を取り出す。intやfloat等の場合に。 | |
// 適当な値を突っ込もうとすると、InvalidArgumentExceptionが発生して停止 | |
//$suit = new Suit('uso800'); | |
//__callStaticを定義してあるのでnewを使わずこんな感じでも書ける(PHP5.3以降) | |
$suit = Suit::SPADE(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment