class and subclass reference question
| From: | Nedjo Rogers | Date: | Tue, 04 Jan 2005 18:59:48 +0000 |
| Subject: | class and subclass reference question | ||
| Groups: | php.pear.dev | ||
| Request: | Send a blank email to pear-dev+get-35336@lists.php.net to get a copy of this message | ||
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