views:

146

answers:

3

Dear all,

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!

+1  A: 

It looks like this is what you're trying to do...

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

        $this->$k = $v;

    }

}
Galen
er... it really odd, just now I also try this way no success, but I try again. It work!. Not sure what happen..@@
Shiro
+6  A: 

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.

Felix Kling
+1: yes that will be better and generic solution
Sarfraz
wow.. thanks! this is great! Thx for Galen and Felix help. I really learn a lot :)
Shiro
Awesome, I always learn something new ;)
henasraf
+1  A: 
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 validation.

Shiro