Page 1 of 1

referring to a containing object...

Posted: Thu Mar 15, 2007 1:59 am
by Kieran Huggins
Hey everyone,

Maybe it's just because it's 3am (or I'm low on caffeine...) but for the life of me I can't seems to figure this out:

I know the example doesn't make a huge amount of sense, but it does in practice (I promise!)

Code: Select all

$thing = new Thing; // I have a thing

$thing->var = new Thing; // the thing contains a thing

$copyOfThing = $thing->var->returnOuterThing(); // I want a reference to $thing returned here

class Thing{

   function returnOuterThing(){
      //..... ???????
   }

}
Thanks!

Posted: Thu Mar 15, 2007 2:35 am
by dude81
Firstly, you will need to define var in the class definition. Secondly (I'm not sure of this either), an object is being assigned to an variable of a class.

Posted: Thu Mar 15, 2007 2:37 am
by Christopher
It's composite/component. I would not do:

Code: Select all

$thing->var = new Thing;
but instead do:

Code: Select all

$thing->attach(new Thing);
were attach() set a parent property.

Posted: Thu Mar 15, 2007 10:23 am
by Kieran Huggins
sorry for the confusion (and terrible example!)

I actually am using both of those methods already.. I'll update the code example:

Code: Select all

$thing = new Thing; // I have a thing

$subThing = $thing->changeFocus();

$origThing = $thing->returnOuterThing();

class Thing{

   var $var;

   function returnOuterThing(){
      //..... ???????
   }

   function changeFocus(){
      $this->var = new Thing; // the thing contains a thing
      return $this->var;
   }

}
when I try setting a parent using:

Code: Select all

function changeFocus(){
      $this->var = new Thing; // the thing contains a thing
      $this->var->parent = $this;
      return $this->var;
   }
I get:
Object of class Thing could not be converted to string
and usnig a reference gives me:

Code: Select all

function changeFocus(){
      $this->var = new Thing; // the thing contains a thing
      $this->var->parent = &$this;
      return $this->var;
   }
I get:
Cannot assign by reference to overloaded object
EDIT: DOH! I can't mix overloading and assigning by reference. When I removed the overloading (__get and __set) it works. While I'm satisfied for now (since I don't yet require overloading) does anyone have a way around this?