Dynamic constants in PHP?

前端 未结 4 2200
迷失自我
迷失自我 2021-02-09 08:36

Is there a way to create a class\'s constants dynamically? I know this sounds a bit odd but let me explain what I\'m trying to do:

  • I have a Enum class who\'s attri
4条回答
  •  醉酒成梦
    2021-02-09 09:17

    Wrap your "enum" values in a singleton and implement the (non-static) magic __get method:

    enum_values = array( //fetch from somewhere
            'one' => 'two',
            'buckle' => 'my shoe!',
        );
      }
    
      function __get($name) {
        return $this->enum_values[$name]; //or throw Exception?
      }
    
      public static function values() {
        return self::singleton()->enum_values; //warning... mutable!
      }
    }
    

    For bonus points, create a (non-OO) function that returns the singleton:

    function DynamicEnums() {
        return DynamicEnums::singleton();
    }
    

    Consumers of "DynamicEnums" would look like:

    echo DynamicEnums::singleton()->one;
    echo DynamicEnums()->one;            //can you feel the magic?
    print_r(DynamicEnums::values());
    

    [edit] More enum-like.

提交回复
热议问题