Skip to content

Instantly share code, notes, and snippets.

@indare
Last active February 23, 2016 03:55
Show Gist options
  • Save indare/c579dbf871ede967f6dd to your computer and use it in GitHub Desktop.
Save indare/c579dbf871ede967f6dd to your computer and use it in GitHub Desktop.
enumっぽいやつ。
<?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;
}
}
<?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;
}
}
<?php
namespace src;
class Names extends Enum
{
CONST A = "hoge";
CONST C = "hige";
}
<?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));
}
}
@indare
Copy link
Author

indare commented Feb 23, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment