首页 > 解决方案 > 在构造中调用其他类是不好的做法吗

问题描述

我最近尝试了解有关 OOP 的更多信息,但我不确定以下内容。

像这样调用构造中的其他类是不好的做法:

class Main{
   function __construct(){
      $this->db = new DatabaseConnection(); 
      $this->rp = new ResponseHandler();
   }

   public function SelectUser( $user_id ){
      ...
      $this->db->query('...') // `query` is a method in DataBaseConnection
      ...
      return $this->rp->msg('...'); // `msg` is a method in ResponseHandler
}

在我看来,这似乎是一种简单而好的方法,但我不知道这是否真的是/一种正确的 OOP 方法。

标签: phpclassoopconstructor

解决方案


如果您知道 Main 类的方法将需要 DatabaseConnection 和 ResponseHandler 来执行它们的工作,那么恕我直言,您的方法完全可以。

因此,您将实现对您的类的用户隐藏。这就是 OOP 的全部意义所在。

我不喜欢通过构造函数进行依赖注入的想法,因为它迫使调用者链上的每个人都知道您的 Main 类需要哪些其他类。


推荐阅读