Dynamic constants in PHP?

前端 未结 4 2203
迷失自我
迷失自我 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:15

    You could do something like Const = $$constant. Then you could set $contant = whatever. OR you could use a protected property since you want it to be dynamic and Constants are not. Example:

    class Foo {
    
    protected $test = '';
    
    function set($bar){
        $this->test = $bar;
    }
    function get($bar){
        return $this->test;
    }
    
    
    }
    
    $foobar = new Foo();
    $foobar->set('test');
    echo $foobar->get('test');
    

提交回复
热议问题