克隆对象为$ this

时间:2010-02-25 06:49:56

标签: php object clone

我想问一下PHP克隆/复制对象到$ this变量。

目前我是MVC的新手,我想做一些像CodeIgniter。

我想直接访问变量。

在我的__construct()中,我总是将全局变量传递给新控制器(类),

例如。

function __construct($mvc)
{
    $this->mvc = $mvc;
}

在$ mvc里面得到了配置对象,vars对象。

例如,目前

function index()
{
    $this->mvc->config['title'];
    $this->mvc->vars['name'];
}

**我想要的更直接**

function index()
{
    $this->config['title'];
    $this->vars['name'];
}

我试过了

function __construct($mvc)
{
    $this = $mvc;
}

function __construct($mvc)
{
    $this = clone $mvc;
}

没有成功。任何想法,我可以关闭$ this-> mvc到$这个级别? 我尝试foreach也没有成功。请帮忙,谢谢!

3 个答案:

答案 0 :(得分:7)

优雅的解决方案是覆盖__get()

public function __get($name) {
    return $this->mvc->$name;
}
每当您尝试访问类的不存在的属性时,都会调用{p> __get()。这样,您就不必复制类中mvc的所有属性(这可能会覆盖类中的属性)。如有必要,您还可以使用property_exists检查$name中是否存在mvc

答案 1 :(得分:1)

看起来这就是你要做的......

function __construct($mvc)
{
    foreach($mvc as $k => $v) {

        $this->$k = $v;

    }

}

答案 2 :(得分:1)

public function __get($name) 
{
    if (array_key_exists($name, $this->mvc)) 
    {
       return $this->mvc->$name;
    }

    $trace = debug_backtrace();
        trigger_error(
            'Undefined property via __get(): ' . $name .
            ' in ' . $trace[0]['file'] .
            ' on line ' . $trace[0]['line'],
            E_USER_NOTICE);
        return NULL;
}

我添加了这个以进行验证。

相关问题