Pass reference to $this in constructor PHP

2019-02-26 05:07发布

问题:

I've got a class called Request. At some point in that class I create a new controller using the following code, passing $this in the constructor:

$controller = new $this->_controllerName($this);

My controller constructor is as follows:

public function __construct(Request $request) {
    parent::__construct($request);

    // More stuff
}

If I modify $request in either this object or its parent object, the values don't change in the object that originally called it. I also tried changing the constructor definition to public function __construct(Request &$request) { (as said on php.net), but that doesn't work either. How can I fix this?

Thanks in advance!

Edit 1: As asked some code that shows what I do with $request. The class has a public property called _response which has a public property called _body. In one of my methods I do the following:

$this->_request->_response->_body = $this->_template->_render();

Now, I need the request from which I called the method to have the same _request property, so that I can get the body.

I forgot to mention that I unset the object right after calling the method, is that a problem?

Edit 2: As pointed out below it does actually work, but it somehow doesn't work anymore when I call it from my __destruct() function. Why is that the case?

回答1:


class Request{
    public $var= 'a';
    public $_controllerName='b';
    public function x(){
        $controller = new $this->_controllerName($this);
    }
}
class controller{
    public function __construct(Request $req){
        $req->var='xyz';
    }
}


class b extends controller{
    public function __construct(Request $req){
        parent::__construct($req);
        print $req->var;
        $req->var='LOL';
    }
}

$r=new Request();
$r->x();
print "\n";
print $r->var;

prints

xyz
LOL

So, it works well in both cases