Page 1 of 1

Access Outer Classes methods

Posted: Mon Dec 08, 2008 1:38 pm
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

Re: Access Outer Classes methods

Posted: Mon Dec 08, 2008 1:55 pm
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)

Re: Access Outer Classes methods

Posted: Mon Dec 08, 2008 2:33 pm
by rgilchrist
Perfect!! Thanks for the swift reply.

Cheers
Rob