【问题标题】:How can I include two classes in each other? [closed]如何在彼此中包含两个类? [关闭]
【发布时间】:2012-12-21 21:29:35
【问题描述】:

假设我有两个 PHP 类,一个名为 gallery,一个名为 image

我想在班级图片中包含班级图片,在班级图片中我想包含班级图片。

如何正确地做到这一点 - 或者最好的方法是什么? 我最终希望能够在类图像的一些方法中使用类库的方法。

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

如何才能做到最好? - 或者有没有完全不同的更好的方法来做这样的事情?

感谢您的回答!

【问题讨论】:

  • class image extends gallery?
  • 我想你想要require_once

标签: php methods include require


【解决方案1】:

Composition .. 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());
      }
   }
}

【讨论】:

  • 感谢您的回答!我是 OOP 的新手,但您的回答无疑向我展示了正确的方向。
【解决方案2】:

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

例如:

// 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 用一个更好的例子打败了我

【讨论】:

  • 我也建议不要使用new Image .. 你知道,设计一个界面等等。
  • 是的。我只是在我记得的时候写。我其实不喜欢 PHP,也不再使用它了。
猜你喜欢
  • 1970-01-01
  • 2010-12-31
  • 1970-01-01
  • 1970-01-01
  • 2012-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多