Flyweight Enums
This file contains 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 MyEnum { | |
private static $initialized = false; | |
private static $values = array(); | |
public static function initialize() { | |
self::$values['MyFirstValue'] = new MyFirstValue(1); | |
self::$values['MySecondValue'] = new MySecondValue(2); | |
self::$values['MyThirdValue'] = new MyThirdValue(3); | |
} | |
public static function __callStatic($name, array $arguments) { | |
if (isset(self::$values[$name])) { | |
return self::$values[$name]; | |
} else { | |
return null; | |
} | |
} | |
private $value = 0; | |
private function __construct($value) { | |
$this->value = $value; | |
} | |
public function __toString() { | |
return get_class($this); | |
} | |
public function value() { | |
return $this->value; | |
} | |
} | |
final class MyFirstValue extends MyEnum {} | |
final class MySecondValue extends MyEnum {} | |
final class MyThirdValue extends MyEnum {} | |
MyEnum::initialize(); |
This file contains 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 | |
require 'flyweight.php'; | |
$first = MyEnum::MyFirstValue(); | |
var_dump($first instanceof MyEnum); // true | |
var_dump($first->value()); // 1 | |
var_dump((string) $first); // 'MyFirstValue' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment