douer9399 2009-09-30 15:15
浏览 15
已采纳

特殊访问封闭对象?

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?

  • 写回答

2条回答 默认 最新

  • doubipeng1336 2009-09-30 15:20
    关注

    This is theoretically impossible. The object is not "enclosed" in anything at all; in an instance of the Enclosing class, you merely enclose a reference to that object. There could be many references all over the place to the same Enclosed instance.

    You might be able to declare Enclosed inside the Enclosing class, but I'm not sure if PHP supports inner classes.

    Otherwise, just pass a reference to the Enclosing object when creating the Enclosed object, and store that in a field of the Enclosed object.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 有偿,学生成绩信息管理系统
  • ¥15 Arduino电机和openmv连接异常
  • ¥15 Arcgis河网分级报错
  • ¥200 java+appium2.1+idea
  • ¥20 请帮我做一个EXE的去重TXT文本
  • ¥15 工价表引用工艺路线,应如何制作py和xml文件
  • ¥15 根据历史数据,推荐问题类型
  • ¥15 需要仿真图,简单的二阶系统实例
  • ¥15 stm32光控照明仿真
  • ¥15 使用人工智能的方法生成满足一定统计参数要求的随机数序列