note 27511 deleted from language.oop by aidan
| From: | aidan@php.net | Date: | Sat, 03 Jul 2004 14:56:12 +0000 |
| Subject: | note 27511 deleted from language.oop by aidan | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-72458@lists.php.net to get a copy of this message | ||
Note Submitter: duncan@NOTINNED.MEAT.emarketeers.com
----
You *can* return a reference from a constructor. You just need to understand exactly what the
"=" and "=&" operators do. Try this:
class parent
{
var $child;
function parent($name)
{
$this->name = $name;
$this->child =& new child($this);
}
}
class child
{
var $parent;
function child(&$parent)
{
$this->parent = &$parent;
}
}
$p = new parent("a");
$p->child->parent->name="b";
echo "Name = $p->name\n"; // Prints "a"
$p =& new parent("a");
$p->child->parent->name="b";
echo "Name = $p->name\n"; // Prints "b"
***
It seems that when a class constructor is called, PHP creates a new instance of the class and then
either hands back a reference to this instance if you use the =& assignment operator, or creates
and hands back a whole new copy if you use the plain = assignment operator.
You should assign new instances with the =& operator unless you have a good reason not to,
because it is faster.