I often have come across this issue with in a MVC sort of setup. If I have a controller and the model needs to access something outside of itself, the model needs to know about the controller. So I often just pass in the controller as a variable in the construct function. But it would be awesome if their were another way.
A thought might be (especially in the controller case), is if Apple is a singleton object, you could just act like you are creating a new Apple. But that isn't really much different then passing it in through the construct function. Justin Scott Giboney On Sat, Oct 8, 2011 at 8:03 AM, Wade Preston Shearer < [email protected]> wrote: > Consider the following code: > > <?php > > class Apple { > public $cat; > > public function __construct() { > $orange = new Orange(); > } > } > > $apple = new Apple(); > > class Orange { > public function dog() { > echo $apple->cat; > } > } > > ?> > > > The echo insider of dog() doesn't work as Orange doesn't have access to > properties and methods of the Apple object. The only way I am aware of to > make it work is to pass the first object in by reference, like this: > > <?php > > class Apple { > public $cat; > > public function __construct() { > $orange = new Orange($this); > } > } > > $apple = new Apple(); > > class Orange { > public $apple; > > public function __construct(&$apple) { > $this->apple = $apple; > } > > public function dog() { > echo $this->apple->cat; > } > } > > ?> > > > Is there any better or simpler (syntactically) way? > > I could pass it into dog() every time I call it like this: > > <?php > > class Apple { > public $cat; > > public function __construct() { > $orange = new Orange(); > } > } > > $apple = new Apple(); > > class Orange { > public function dog(&$apple) { > echo $apple->cat; > } > } > > $apple->orange->dog($apple); > > ?> > > > That gets me the simplicity I want insider of dog(), but adds complexity > ouside of dog each time I have to call it and complicates things with other > variables I have to pass in. Any way to pass it in automatically? I'm > thinking of __set and overloading concepts but haven't been able to come up > with a solution. > > _______________________________________________ > > UPHPU mailing list > [email protected] > http://uphpu.org/mailman/listinfo/uphpu > IRC: #uphpu on irc.freenode.net > _______________________________________________ UPHPU mailing list [email protected] http://uphpu.org/mailman/listinfo/uphpu IRC: #uphpu on irc.freenode.net
