Use of classes inside other classes

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
Qense
Forum Newbie
Posts: 3
Joined: Mon Mar 24, 2008 6:31 am
Location: Veenwouden, The Netherlands

Use of classes inside other classes

Post by Qense »

For a script I'm working on I need to use a class(the one that reports errors) inside another class, both defined in the same file at the same 'level', the main program. For that I use global. But it doesn't work. Although in another class this does work, it seems that the changes don't apply. I call a function to register an error, but the error isn't registered somehow. When I asked at ##php @ freenode I just got a the term Design Patterns, but I don't know what I can do with that to solve the problem since it's something different.
Any thoughts?
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Use of classes inside other classes

Post by Christopher »

You can do:

Code: Select all

class A {
     function __construct ($b) {
          $this->b = $b:
     }
     function foo () {
          echo 'foo':
          $this->b->bar();
     }
}
 
class B {
     function bar () {
          echo 'bar':
     }
}
 
$b = new B();
$a = new A($b);
$a->foo();
(#10850)
User avatar
Qense
Forum Newbie
Posts: 3
Joined: Mon Mar 24, 2008 6:31 am
Location: Veenwouden, The Netherlands

Re: Use of classes inside other classes

Post by Qense »

But is the class B inside class A a copy of class $b?
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Use of classes inside other classes

Post by Christopher »

They are the same object. A and B are classes. $a and $b are objects -- instances of those classes. A class is code. An object allocates memory for data the functions in the class operate on.
(#10850)
Post Reply