Clone object $ this

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

I'm currently new to MVC, I would like to do something like CodeIgniter.

I would like to direct access to a variable.

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

eg.

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

inside the $ mvc configuration object, the vars object.

for example now

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 tried

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

or

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

it is not successful. any idea i can close $ this-> mvc to $ this level? I also try not to succeed. Please help, thanks!

+3
source share
3 answers

An elegant solution would be to override __get():

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

__get() , . , mvc ( ). , $name mvc property_exists.

+7

, , ...

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

        $this->$k = $v;

    }

}
+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;
}

I added this for verification.

+1
source

Source: https://habr.com/ru/post/1734371/


All Articles