dongwopu8210 2015-04-16 00:46
浏览 48
已采纳

在Yii2中在运行时声明类属性

I have a class that extends from Yii2's Model and I need to declare a class public property in the constructor, but I'm hitting a problem.

When I call

class Test extends \yii\base\Model {
    public function __constructor() {
        $test = "test_prop";
        $this->{$test} = null; // create $this->test_prop;
    }
}

Yii tries to call, from what I understand, the getter method of this property, which of course doesn't exist, so I hit this exception.

Also, when I actually do $this->{$test} = null;, this method gets called.

My question is: Is there a way to declare a class public property in another way? Maybe some Reflexion trick?

  • 写回答

3条回答 默认 最新

  • duanci5913 2015-04-16 00:52
    关注

    You could override getter/setter, e.g. :

    class Test extends \yii\base\Model
    {
        private $_attributes = ['test_prop' => null];
    
        public function __get($name)
        {
            if (array_key_exists($name, $this->_attributes))
                return $this->_attributes[$name];
    
            return parent::__get($name);
        }
    
        public function __set($name, $value)
        {
            if (array_key_exists($name, $this->_attributes))
                $this->_attributes[$name] = $value;
    
            else parent::__set($name, $value);
        }
    }
    

    You could also create a behavior...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部