在对象中创建动态属性

时间:2013-01-21 11:23:47

标签: php models controllers

我使用了cakePHP,它具有一个很好的功能,其中模型(如果存在已经作为控制器中的属性创建),因此有效地我可以在我的控制器中访问名为$ this-> model_name的属性而无需创建模型对象的一个​​实例。

根据我的理解,必须在类中定义所有属性才能使用它,那么还有另一种方法可以让我完成上述操作吗?

  // Sample code:
  <?php
  class controller {
        public function create_model($model_name) {
              // Assuming that I have spl_autoload enabled to achieve the below:
              $this->$$model_name = new model_name();      
        }
  }

1 个答案:

答案 0 :(得分:0)

您可以使用魔术方法执行此类操作(请查看_set() _get()

以下是一些示例代码:

class Controller
{
    protected $models;

    public function __get($key)
    {
        return $this->models[$key];
    }

    public function __set($key, $value)
    {
        $this->models[$key] = $value;
    }
}

您可以在__set()__get()中实现自己的功能。您可以使用$this->my_model = $something;设置数据。

以下是针对您的具体示例量身定制的内容:

public function __get($key) // you will only need __get() now
    {

        if (array_key_exists($key, $this->models) && $this->models[$key] instanceof $key) { 
            return $this->models[$key];
        } else {
            $this->models[$key] = new $key;
            return $this->models[$key];
        }

    }

现在,$ this-&gt; my_model尝试实例化my_model(如果它不存在),并返回当前对象(如果存在)。也许不是最好的解决方案,但是在这里添加它可以让你理解它是如何工作的。

相关问题