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 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料