在 PHP 构造函数中传递对 $this 的引用
我有一个名为 Request
的类。在该类中的某个时刻,我使用以下代码创建一个新控制器,并在构造函数中传递 $this
:
$controller = new $this->_controllerName($this);
我的控制器构造函数如下:
public function __construct(Request $request) {
parent::__construct($request);
// More stuff
}
如果我修改 $request
无论是该对象还是其父对象,最初调用它的对象中的值都不会更改。我还尝试将构造函数定义更改为 public function __construct(Request &$request) {
(如 php.net),但这也不起作用。我该如何解决这个问题?
提前致谢!
编辑1:正如所询问的一些代码,显示了我对$request
所做的事情。该类有一个名为 _response
的公共属性,它还有一个名为 _body
的公共属性。在我的方法之一中,我执行以下操作:
$this->_request->_response->_body = $this->_template->_render();
现在,我需要调用该方法的请求具有相同的 _request
属性,以便我可以获得正文。
我忘了提到我在调用该方法后立即取消了对象的设置,这是一个问题吗?
编辑2:正如下面指出的,它确实有效,但当我从__destruct()
函数调用它时,它不知何故不再起作用。为什么会这样呢?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
所以
,在这两种情况下都效果很好
prints
So, it works well in both cases