1. rub1n_83 - 02 Марта, 2017 - 17:24:39 - перейти к сообщению
В интернете много похожих классов, но все они без реализации значения __default как в SplEnum. Может кто-нибудь показать как правильно реализовать __constructor такого класса?
2. armancho7777777 - 03 Марта, 2017 - 08:16:51 - перейти к сообщению
Exceptions (Отобразить)
PHP:
скопировать код в буфер обмена
скопировать код в буфер обмена
- abstract class EnumValueException extends InvalidArgumentException
- {
- /**
- * @var Enum
- */
- protected $_enum;
- public function __construct(Enum $enum)
- {
- parent::__construct();
- $this->_enum = $enum;
- }
- /**
- * @return Enum
- */
- public function getEnum()
- {
- return $this->_enum;
- }
- }
- class EnumValueNotInException extends EnumValueException {}
- class EnumValueTypeException extends EnumValueException {}
abstract class Enum (Отобразить)
PHP:
скопировать код в буфер обмена
скопировать код в буфер обмена
- abstract class Enum
- {
- const __default = NULL;
- protected $_value;
- /**
- * Enum constructor.
- * @param string $value null
- * @param bool $strict false
- */
- public function __construct($value = NULL, $strict = false) {
- !$value ? ($this->_value = static::__default)
- : $this->setValue($value, $strict);
- }
- public function __toString() {
- }
- /**
- * @return string
- */
- public function name() {
- }
- /**
- * @return mixed
- */
- public function getValue() {
- return $this->_value;
- }
- /**
- * @param mixed $value
- * @param bool $strict false
- * @return $this
- * @throws EnumValueNotInException
- * @throws EnumValueTypeException
- */
- public function setValue($value, $strict = false)
- {
- if(!static::_exists($value)) {
- throw new EnumValueNotInException($this);
- }
- if($strict && !static::_validateType($value)){
- throw new EnumValueTypeException($this);
- }
- $this->_value = $value;
- return $this;
- }
- /**
- * @param bool $includeDefault false
- * @return array
- */
- public static function values($includeDefault = false)
- {
- $values = (new ReflectionClass(static::class))->getConstants();
- if(!$includeDefault) {
- }
- return $values;
- }
- /**
- * @param bool $includeDefault false
- * @return array
- */
- public static function names($includeDefault = false) {
- }
- /**
- * @param mixed $value
- * @return bool
- */
- protected static function _exists($value) {
- }
- /**
- * @param mixed $value
- * @return bool
- */
- protected static function _validateType($value) {
- }
- }
Enumerate class Month (Отобразить)
PHP:
скопировать код в буфер обмена
скопировать код в буфер обмена
- class Month extends Enum
- {
- const __default = self::January;
- const January = 1;
- const February = 2;
- const March = 3;
- const April = 4;
- const May = 5;
- const June = 6;
- const July = 7;
- const August = 8;
- const September = 9;
- const October = 10;
- const November = 11;
- const December = 12;
- }