代码之家  ›  专栏  ›  技术社区  ›  Shiro

将对象克隆到$this

  •  3
  • Shiro  · 技术社区  · 15 年前

    我想问一个关于php克隆/复制对象到$this变量的问题。

    目前我是MVC的新成员,我想做一些类似代码点火器的事情。

    我想直接访问变量。

    在my uu construct()中,我总是将内部的全局变量传递给新的控制器(类)。

    如。

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

    在$mvc got config对象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关闭到$this级别? 我也尝试过没有成功。请帮忙,谢谢!

    3 回复  |  直到 15 年前
        1
  •  7
  •   Felix Kling    15 年前

    一个优雅的解决方案是 __get() :

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

    γ-() 每当尝试访问类中不存在的属性时都会调用。这样,您就不必复制 mvc 在类中(可能会覆盖类中的属性)。如有必要,您还可以检查 $name 存在于 MVC 具有 property_exists .

        2
  •  1
  •   Galen    15 年前

    看起来这就是你想做的…

    function __construct($mvc)
    {
        foreach($mvc as $k => $v) {
    
            $this->$k = $v;
    
        }
    
    }
    
        3
  •  1
  •   Shiro    15 年前
    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;
    }
    

    我添加了这个进行验证。