The code:
<?
class foo {
var $bar;
function foo() {
$GLOBALS["secondobject"] = &$this;
if (!$this->bar)
$this->bar = "Bleh bleh blah";
}
}
$firstobject = new foo();
$secondobject->bar .= " buh";
print "<hr><pre>";
var_dump($firstobject, "firstobject");
print "</pre><hr><pre>";
var_dump($secondobject, "secondobject");
print "</pre><hr>";
?>
Produces:
object(foo)(1) {
["bar"]=>
string(14) "Bleh bleh blah"
}
string(11) "firstobject"
object(foo)(1) {
["bar"]=>
string(18) "Bleh bleh blah buh"
}
string(12) "secondobject"
While the code:
<?
class foo {
var $bar;
function foo() {
$GLOBALS["secondobject"] = &$this;
if (!$this->bar)
$this->bar = "Bleh bleh blah";
}
}
$firstobject = new foo();
$firstobject->foo();
$secondobject->bar .= " buh";
print "<hr><pre>";
var_dump($firstobject, "firstobject");
print "</pre><hr><pre>";
var_dump($secondobject, "secondobject");
print "</pre><hr>";
?>
produces:
object(foo)(1) {
["bar"]=>
string(18) "Bleh bleh blah buh"
}
string(11) "firstobject"
object(foo)(1) {
["bar"]=>
string(18) "Bleh bleh blah buh"
}
string(12) "secondobject"
Why doesn't the constructor get runned properly at object creation...
I have to call the constructor explicitly for the reference to get properly set up...
In the constructor of the class I make an attempt to assign the global value $secondclass a reference to the object itself with the following line:
$GLOBALS["secondobject"] = &$this;
(Passing by reference)
This should make the variable $secondobject identic to $firstobject after the line
$firstobject = new foo();
which should initialize the constructor. However this does not seem to be the case.
This only creates $secondobject as a duplicate of $firstobject...
For instance calling
$secondobject->bar .= "buhu";
does not append "buhu" to $firstobject->bar
But if I after creating the object with
$firstobject = new foo();
calls the constructor again with
$firstobject->foo();
then $secondobject seem to be a reference to $firstobject...
after that
$secondobject->bar .= "buhu";
appends "buhu" to $firstobject->bar...
It confuses the hell out of me....
So what I suspect is that passing &$this out of the constructor does not necessary make the desired effect...