Last active
February 23, 2016 03:55
-
-
Save indare/c579dbf871ede967f6dd to your computer and use it in GitHub Desktop.
enumっぽいやつ。
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 | |
namespace src; | |
use InvalidArgumentException; | |
use ReflectionObject; | |
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 | |
namespace src; | |
class Getter | |
{ | |
/** | |
* @param names $name | |
* @return names | |
*/ | |
public function piyo(names $name) | |
{ | |
return $name; | |
} | |
/** | |
* @param names $name | |
* @return bool | |
*/ | |
public function check(names $name) | |
{ | |
return $name instanceof names; | |
} | |
} |
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 | |
namespace src; | |
class Names extends Enum | |
{ | |
CONST A = "hoge"; | |
CONST C = "hige"; | |
} |
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 | |
namespace src; | |
use PHPUnit_Framework_TestCase; | |
class test extends PHPUnit_Framework_TestCase | |
{ | |
/** @test */ | |
public function test1() | |
{ | |
$name = new Names(Names::A); | |
$getter = new Getter(); | |
$this->assertEquals('hoge', $getter->piyo($name)); | |
} | |
/** @test */ | |
public function test2() | |
{ | |
$name = new Names(Names::C); | |
$getter = new Getter(); | |
$this->assertTrue($getter->check($name)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
参考資料はこちら。
http://qiita.com/Hiraku/items/71e385b56dcaa37629fe