Access Outer Classes methods

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
rgilchrist
Forum Newbie
Posts: 4
Joined: Mon Jul 30, 2007 3:47 pm

Access Outer Classes methods

Post by rgilchrist »

Hi
I have searched for hours trying to find the answer to this and it seems such an obvious question, I can't believe I haven't found the answer.

If I have 2 classes, and one class is created inside the other, how do I access the methods and variables of the outer class from the inner class. A bit of code probably explains it better

class Outer{
public function __construct(){
$inner = new Inner();
}

function moo(){
print "Moo Moo";
}

}

class Inner{
//How do I call Outer's moo() from here?

}

Thanks in Advance

Cheers
Rob
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: Access Outer Classes methods

Post by Eran »

Those classes represent separate scopes, and one should not be aware that's it's being called from inside the other. You could supply the object instance of the first class to the other through the constructor or a setter method:

Code: Select all

 
class Outer{
    public function __construct(){
          $inner = new Inner($this);
    }
    public function moo(){
         print "Moo Moo";
    }
}
 
class Inner{
     protected $outer;
     public function __construct(Outer $outer) {
           $this -> outer = $outer;
     } 
     
     public function cowSays() {
          $this -> outer -> moo();
     }
}
 
 
(By the way, in the future please wrap your code with

Code: Select all

tags so it will be displayed in formatted form)
User avatar
rgilchrist
Forum Newbie
Posts: 4
Joined: Mon Jul 30, 2007 3:47 pm

Re: Access Outer Classes methods

Post by rgilchrist »

Perfect!! Thanks for the swift reply.

Cheers
Rob
Post Reply