Created
October 8, 2014 16:10
-
-
Save jm42/f6a8988c6aa874b0fc14 to your computer and use it in GitHub Desktop.
Named Tuple
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 | |
| class NamedTuple { | |
| public static $__instances = array(); | |
| private $uuid; | |
| private $values = array(); | |
| public function __construct() { | |
| $found = false; | |
| foreach (static::$__instances as $uuid => $keys) { | |
| if (is_a($this, 'NamedTuple_' . $uuid)) { | |
| $found = true; | |
| break; | |
| } | |
| } | |
| if (!$found) { | |
| throw new LogicException('UUID not found'); | |
| } | |
| $values = func_get_args(); | |
| foreach ($keys as $index => $key) { | |
| $this->values[$key] = isset($values[$index]) | |
| ? $values[$index] : null; | |
| } | |
| $this->uuid = $uuid; | |
| } | |
| public function __get($key) { | |
| if (!isset($this->$key)) { | |
| throw new LogicException('Key "' . $key . '" not found'); | |
| } | |
| return $this->values[$key]; | |
| } | |
| public function __set($key, $value) { | |
| if (!isset($this->$key)) { | |
| throw new LogicException('Key "' . $key . '" not found'); | |
| } | |
| $this->values[$key] = $value; | |
| } | |
| public function __isset($key) { | |
| return isset($this->values[$key]); | |
| } | |
| } | |
| function namedtuple() { | |
| $uuid = uniqid(); | |
| NamedTuple::$__instances[$uuid] = func_get_args(); | |
| class_alias('NamedTuple', 'NamedTuple_' . $uuid, false); | |
| return 'NamedTuple_' . $uuid; | |
| } | |
| $Request = namedtuple('method', 'uri'); | |
| $request = new $Request('GET', '/'); | |
| assert($request->method === 'GET'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment