问题
Possible Duplicate:
Pass reference to $this in constructor PHP
I'm working on a simple PHP framework as a learning project. I've got a request object with a method called _execute()
. In that method I (among other things) create an object called pageController, call a method on it, and remove the object using the following code:
$controller = new $this->_controllerName($this);
call_user_func(array($controller, $this->_methodName));
unset($controller);
As you can see I pass the current object to the constructor of the new pageController. My constructor is as follows:
public function __construct(Request $request) {
parent::__construct($request);
// More stuff
}
The parent's controller is like this:
public function __construct(Request $request) {
$this->_request = $request;
}
This all works fine, but there is a problem with my destructor. In the pageController I've also got two other methods:
public function __destruct() {
$this->_render();
}
public function _render($templateName = 'default') {
$this->_request->_response->_body = $this->_template->_render();
}
My _render()
method works great if I call it from within another method in pageController: I can then get the response body from the initial request object using $this->_response->_body
. When I call the _render()
method from my destructor though, the changes are not changed in the request object. When I call print_r()
right after the call to _render()
, the changes are somehow visible...
Summarized: Any changes I make to the _request
property in the destructor are somehow not changed in the initial request object, which references to the same, since objects are (almost) always not copied but referenced. What am I doing wrong?
Note: I asked a similar question before here, but that questions was not specific enough (because I didn't fully understand the problem then and thanks to some bad testing by myself). I figured I should ask a new, specific, direct question so someone can hopefully help me out.
回答1:
What PHP version are you using? I was not able to duplicate your issue on 5.3.6
with the following code:
class Foo {
public function __construct(Bar $bar) {
$this->bar = $bar;
}
public function __destruct() {
$this->bar->value = 'set by Foo::__destruct';
}
}
class Bar {
public function __construct() {
$this->value = 'set by Bar::__construct';
}
}
$bar = new Bar();
$foo = new Foo($bar);
print $bar->value . PHP_EOL; // => 'set by Bar::__construct'
unset($foo);
print $bar->value . PHP_EOL; // => 'set by Foo::__destruct'
Is that along the same lines as what you are attempting to do. If it is... it sounds like maybe some other part of you application logic is interfering.
来源:https://stackoverflow.com/questions/6986334/modifications-in-object-destruct-not-saved-php