dongwopu8210 2015-04-16 08: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 08: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条)

报告相同问题?

悬赏问题

  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘