Page 1 of 1

Class within a Class

Posted: Fri May 28, 2004 8:33 pm
by Gen-ik
I've been using Classes for a while now and have never thought about asking this before for some reason but... is it possible to have a Class within another Class?

For example, let's say I have a Class named "Navigation" and within the Navigation Class I wanted another Class named "SubNav" which Navigation could use within itself?

Hope that's understandable ;)

Posted: Fri May 28, 2004 8:40 pm
by kettle_drum
If you want sub-class to use class methods and attributes then you simply have it use Class as its parent:

Code: Select all

class Daddy {
   //a few functions etc
}

class Son extends Daddy {
   //a few more functions and you can also call any function that is in the Daddy class.
}
If you dont want to inherit then you can pass classes to a class:

Code: Select all

class Test {
   var $some_class;
   
   function Test($class){
      $this->some_class = $class;
   }
}

$dad = new Daddy();
$test = new Test($dad);
Is that what you wanted?

Posted: Fri May 28, 2004 9:26 pm
by Gen-ik
Yes, that second example is perfect... cheers mate.

Posted: Sat May 29, 2004 8:00 am
by kettle_drum
Np, i pass classes to classes all the time and a few things i have discovered from trial and error are:

1) If your passing more than one class, pass them as an array - it makes things so much neater and easier to access.

2) Pass the objects as references so another copy of the class isnt made, and you can also add/edit values in the original class ($test = new Test(&$dad);)

Posted: Sat May 29, 2004 8:59 am
by Gen-ik
Thanks kettle_drum, that should make things a bit easier to keep track of :)

Posted: Sat May 29, 2004 2:19 pm
by McGruff