如何在彼此中包含两个类?

时间:2012-12-21 21:29:36

标签: php methods include require

假设我有两个PHP类一个名为图库,一个名为图像

在课堂图片中我想要包含课堂图库,在课堂图库中我想要包含课堂图片。

如何正确完成 - 或者最好的方法是什么? 我最终希望能够在类图像的某些方法中使用类库的方法。

例如:我在两个类中都有一个方法“删除”。 在班级图书馆中,该方法用于删除由ID选择的特定图库。但是,类图像中的 方法删除还会检查删除的图像是否是图库中的最后一个图像 - 如果是这样,则应通过将id传递给类库的delete方法来删除此图库。 / p>

这怎么可能做得最好? - 或者是否有完全不同的更好的方法来做这样的事情?

谢谢你的回答!

2 个答案:

答案 0 :(得分:3)

组合.. image实例有一个它所属的图库的实例(如果它可以属于多个使事情复杂化的图库)。

class Image {
   private $gallery;
   private $db;
   public function __construct(Gallery $gallery, DB $db) {
      $this->gallery = $gallery;
      $this->db = $db;
   }

   public function delete($id) {
      $this->db->deleteImage($id);
      if ($this->gallery->isEmpty()) {
         $this->gallery->delete($this->gallery->getID());
      }
   }
}

答案 1 :(得分:0)

使您的图库成为实例化图像类的唯一位置,然后在图像的构造函数中设置一个属性,以便图库传递对自身的引用。

例如:

// in class Image
...
function Image($gallery) {
    $this->gallery = $gallery;
}
...

// in class Gallery
...
function get_image($id) {
    $img = new Image($this);
    ...
    return $img;
}
...

$image = $gallery->get_image(1);

修改 看起来像ExplosionPills用一个更好的例子击败了我