note 27511 added to language.oop

From: Date: Mon, 09 Dec 2002 13:48:01 +0000
Subject: note 27511 added to language.oop
Groups: php.notes 
Request: Send a blank email to php-notes+get-40569@lists.php.net to get a copy of this message
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. -- http://www.php.net/manual/en/language.oop.php http://master.php.net/manage/user-notes.php?action=edit+27511 http://master.php.net/manage/user-notes.php?action=delete+27511 http://master.php.net/manage/user-notes.php?action=reject+27511

« previous php.notes (#40569) next »