Class within a Class

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
Gen-ik
DevNet Resident
Posts: 1059
Joined: Mon Aug 12, 2002 7:08 pm
Location: London. UK.

Class within a Class

Post 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 ;)
kettle_drum
DevNet Resident
Posts: 1150
Joined: Sun Jul 20, 2003 9:25 pm
Location: West Yorkshire, England

Post 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?
Gen-ik
DevNet Resident
Posts: 1059
Joined: Mon Aug 12, 2002 7:08 pm
Location: London. UK.

Post by Gen-ik »

Yes, that second example is perfect... cheers mate.
kettle_drum
DevNet Resident
Posts: 1150
Joined: Sun Jul 20, 2003 9:25 pm
Location: West Yorkshire, England

Post 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);)
Gen-ik
DevNet Resident
Posts: 1059
Joined: Mon Aug 12, 2002 7:08 pm
Location: London. UK.

Post by Gen-ik »

Thanks kettle_drum, that should make things a bit easier to keep track of :)
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Post by McGruff »

Post Reply