note 97052 added to language.oop5.references
| From: | HayleyWatson at osu1 dot php dot net | Date: | Tue, 30 Mar 2010 03:21:36 +0000 |
| Subject: | note 97052 added to language.oop5.references | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-167518@lists.php.net to get a copy of this message | ||
Using &$this can result in some weird and counter-intuitive behaviour - it starts lying to you.
<?php
class Bar
{
public $prop = 42;
}
class Foo
{
public $prop = 17;
function boom()
{
$bar = &$this;
echo "\$bar is an alias of \$this, a Foo.\n";
echo '$this is a ', get_class($this), '; $bar is a ', get_class($bar),
"\n";
echo "Are they the same object? ", ($bar === $this ? "Yes\n" :
"No\n");
echo "Are they equal? ", ($bar === $this ? "Yes\n" : "No\n");
echo '$this says its prop value is ';
echo $this->prop;
echo ' and $bar says it is ';
echo $bar->prop;
echo "\n";
echo "\n";
$bar = new Bar;
echo "\$bar has been made into a new Bar.\n";
echo '$this is a ', get_class($this), '; $bar is a ', get_class($bar),
"\n";
echo "Are they the same object? ", ($bar === $this ? "Yes\n" :
"No\n");
echo "Are they equal? ", ($bar === $this ? "Yes\n" : "No\n");
echo '$this says its prop value is ';
echo $this->prop;
echo ' and $bar says it is ';
echo $bar->prop;
echo "\n";
}
}
$t = new Foo;
$t->boom();
?>
In the above $this claims to be a Bar (in fact it claims to be the very same object that $bar is),
while still having all the properties and methods of a Foo.
Fortunately it doesn't persist beyond the method where you committed the faux pas.
<?php
echo get_class($t), "\t", $t->prop;
?>
----
Server IP: 69.147.83.197
Probable Submitter: 125.237.144.87
----
Manual Page -- http://www.php.net/manual/en/language.oop5.references.php
Edit -- https://master.php.net/note/edit/97052
Del: integrated -- https://master.php.net/note/delete/97052/integrated
Del: useless -- https://master.php.net/note/delete/97052/useless
Del: bad code -- https://master.php.net/note/delete/97052/bad+code
Del: spam -- https://master.php.net/note/delete/97052/spam
Del: non-english -- https://master.php.net/note/delete/97052/non-english
Del: in docs -- https://master.php.net/note/delete/97052/in+docs
Del: other reasons-- https://master.php.net/note/delete/97052
Reject -- https://master.php.net/note/reject/97052
Search -- https://master.php.net/manage/user-notes.php