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
Access Outer Classes methods
Moderator: General Moderators
Re: Access Outer Classes methods
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:
(By the way, in the future please wrap your code with
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();
}
}
Code: Select all
tags so it will be displayed in formatted form)- rgilchrist
- Forum Newbie
- Posts: 4
- Joined: Mon Jul 30, 2007 3:47 pm
Re: Access Outer Classes methods
Perfect!! Thanks for the swift reply.
Cheers
Rob
Cheers
Rob