Skip to content

Instantly share code, notes, and snippets.

@hirak
Created March 7, 2013 16:27
Show Gist options
  • Save hirak/5109317 to your computer and use it in GitHub Desktop.
Save hirak/5109317 to your computer and use it in GitHub Desktop.
PHPで列挙型(enum)を作る ref: http://qiita.com/items/71e385b56dcaa37629fe
<?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;
}
}
<?php
function doSomething(Suit $suit) {
//Suitというタイプヒントによって、
//$suitは必ず4種類のうちのどれかだと保証されている
}
<?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