$this in constructors
| From: | Mike Heath | Date: | Wed, 25 Oct 2000 20:59:35 +0000 |
| Subject: | $this in constructors | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-21929@lists.php.net to get a copy of this message | ||
I'm having problems with $this in class constructors (and apparantly I'm not
the only one. Look at bug numbers 6529 and 7455 in the bug database at
bugs.php.net and I added bug #7454).
Apparantly if you assign a reference to $this in the constructor you
actually get a copy and not a reference. Does anybody know more about this?
Any workarounds? I've E-mailed a couple of people that posted the bugs and
they've either been told they're using references wrong, which I don't
understand (of course, I've been mixed up by references before), or haven't
heard anything. Any help I can get here?
Here's a code example of one of the problems (taken from bug 7455, it's a
much better example than the one I used):
<?
global $GlobaBlow; //will hold the reference of $blow
class foobar {
var $State; //Holds the current state of an instanticated class
function foobar() {
$this->work(); //Sets GlobalBlow to the reference of the instanciated
class
$this->State = "In Constructor"; //Sets the state of the instanciated
class to "In Constructor"
}
function work() {
$GLOBALS["GlobalBlow"] =& $this; //Assigns the Global variable the
reference to this instanciated class
}
}
$blow = new foobar(); //creates a new foobar
//$blow->work();
$blow->State = "Global"; //sets the state of the instanciated foobar to
"Global"
echo $GlobalBlow->State; //should display "Global" but instead displays "In
Constructor"
?>
What happens is that the method work() assigns a reference to $this. When
it's called from the constructor is ends up making a copy NOT a reference.
If you instantiate the class and then call the method work (it's commented
out in the code), everything works just fine.
Anyway, just looking for some insight beyond my own regarding this bug.
Thanks,
Mike