referring to a containing object...

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

referring to a containing object...

Post 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!
User avatar
dude81
Forum Regular
Posts: 509
Joined: Mon Aug 29, 2005 6:26 am
Location: Pearls City

Post 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.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post 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.
(#10850)
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post 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?
Post Reply