Search code examples
phpobjectclone

Clone object to $this


I would like to ask about PHP clone / copy object to $this variable.

Currently I am new in MVC, I would like to do something like CodeIgniter.

I would like to direct access to the variable.

in my __construct(), i always pass the global variable inside to the new controller (class),

eg.

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

inside the $mvc got config object, vars object.

e.g, currently

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

** what I want is more direct**

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

I had try

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

or

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

it not successfully. any idea, I can close $this->mvc to $this level? I try foreach also no success. Please help, Thank!


Solution

  • An elegant solution would be to override __get():

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

    __get() gets called whenever you to try access a non-existent property of your class. This way, you don't have to copy every property of mvc inside your class (which might override properties in your class). If necessary you can also check whether $name exists in mvc with property_exists.