Is there a way, in PHP5.3, for an object $enclosed to know which object $enclosing that it is inside of? Essentially I want to make some variables of $enclosing be accessible only to $enclosed without specifically passing those vars in.
class Enclosing {
private $enclosed;//Enclosed object
private $othervar;
function __construct($a,$b){
$this->othervar=$a;
$this->enclosed= new Enclosed($b);
}
}
class Enclosed {
private $myvar;
function __construct($a){
$this->myvar=$a;
}
function where_am_i() {//get reference to Enclosing object
//????
}
}
Background:
I am working on a Calendar that can display multiple Schedules which have multiple, possibly recurring Events. I am using PHPs DateTime, DateInterval and DatePeriod objects for date handling (they make dealing with timezones and recurrence easier despite their other drawbacks). Currently my design goes like this:
A Calendar object has a DatePeriod called $window which contains all the display dates. e.g. the month of May, 1957.
The Calendar also has an array $schedules of Schedule objects. Each member of $schedules must be aware of $window. So I implemented the Observer pattern between Calendar and Schedule.
Similarly each Schedule has an array $events of Events, which because they may be recurring, must also be aware of $window. So I implemented the Observer pattern between Schedule and Event.
All of this means that I have a cascade of copying the $window to multiple other objects every time it changes.
It would be much more efficient if the Events in $events knew who their enclosing Schedule was and that Schedule knew who its enclosing Calendar was. Then when these objects needed to use $window they could just ask for it.
Any thoughts on a good way of making this happen? Is there a pattern I can refer to?
This is theoretically impossible. The object is not “enclosed” in anything at all; in an instance of the
Enclosingclass, you merely enclose a reference to that object. There could be many references all over the place to the sameEnclosedinstance.You might be able to declare
Enclosedinside theEnclosingclass, but I’m not sure if PHP supports inner classes.Otherwise, just pass a reference to the
Enclosingobject when creating theEnclosedobject, and store that in a field of theEnclosedobject.