Re: class and subclass reference question
| From: | Jan Jonas | Date: | Wed, 05 Jan 2005 00:09:55 +0000 |
| Subject: | Re: class and subclass reference question | ||
| References: | 1 | Groups: | php.pear.dev |
| Request: | Send a blank email to pear-dev+get-35343@lists.php.net to get a copy of this message | ||
Try
$newObj =& new PrincipalClass('firstName');
instead of
$newObj = new PrincipalClass('firstName');
and the output is "secondName".
In your version $newObject is a copy from the PrincipalClass-Object.
So $newObj->subClass->setName('secondName'); changes the name of the PrincipalClass-Object you created and not of the Object in the variable $newObject (because it's not a refference, but a copy)
Jan
Nedjo Rogers wrote:
I'm drafting a PEAR package proposal in PHP 4 (for providing a standards-compliant "web map service" interface to the Image_GIS package) and could use some help with subclass references. When creating a subclass object, I wish to create a reference to the principal object so that the subclass object can, e.g., update properties in the principal object. The tutorial at http://www.phppatterns.com/index.php/article/articleview/23/1/2/ explains how this can be done from external calls (i.e., not internal to the classes) using the & reference operator. However, when I try to pass references within classes, I get copies instead (e.g., changes made by subclass objects are not registered with the principal object). An example: <?php class PrincipalClass{ var $name; var $size; var $subClass; function PrincipalClass($name) {$this->name = $name; $this->subClass =& new SubClass($this);} function printName($name) {echo $this->name;} } class SubClass{ var $principalClass; function SubClass(&$principalClass) {$this->principalClass =& $principalClass;} function setName($name) {$this->principalClass->name = $name;} } $newObj = new PrincipalClass('firstName'); $newObj->subClass->setName('secondName'); $newObj->printName(); // Output is 'firstName' and not 'secondName'. ?> Is there a standard approach to this problem? Thanks for any help, Nedjo Rogers Learning Technologies Developer GroundWorks Learning Centre Victoria, BC, Canada nedjo@gworks.ca