本文介绍了在构造函数PHP中传递对$ this的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个叫做Request的类.在该类的某个时刻,我使用以下代码创建一个新的控制器,并在构造函数中传递$this:

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
}

如果我在此对象或其父对象中修改了$request,则在最初调用它的对象中值不会更改.我还尝试将构造函数定义更改为public function __construct(Request &$request) {(如 php.net ),但这也不起作用.我该如何解决?

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?

提前谢谢!

根据要求,一些代码显示了我对$request的处理方式.该类具有一个称为_response的公共属性,而该公共属性具有一个名为_body的公共属性.在我的一种方法中,我执行以下操作:

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();

现在,我需要从中调用方法的请求具有相同的_request属性,以便可以获取主体.

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?

正如下面所指出的,它确实可以工作,但是当我从__destruct()函数调用它时,它以某种方式不再起作用.为什么会这样呢?

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?

推荐答案


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;

打印

xyz
LOL

因此,在两种情况下都可以正常工作

So, it works well in both cases

这篇关于在构造函数PHP中传递对$ this的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 14:43