php - 在构造中调用其他类是不好的做法吗
问题描述
我最近尝试了解有关 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 方法。
解决方案
如果您知道 Main 类的方法将需要 DatabaseConnection 和 ResponseHandler 来执行它们的工作,那么恕我直言,您的方法完全可以。
因此,您将实现对您的类的用户隐藏。这就是 OOP 的全部意义所在。
我不喜欢通过构造函数进行依赖注入的想法,因为它迫使调用者链上的每个人都知道您的 Main 类需要哪些其他类。
推荐阅读
- javascript - 反应滚动到一个没有反应路由器和最基本代码的组件
- javascript - 当我尝试在我的 chrome 扩展中使用 https://apis.google.com/js/api.js 时出错
- java - 包名无效
- android - 如何使用 OpenGL ES 着色器转换 rgbaToYuv 然后渲染到 ImageReader 的表面
- c++ - 我们可以将 c++ 标准编译与 MSVC 混合使用吗?
- python - python - 如何在python中的空位置将字符串拆分为长度相等的0对?
- javascript - 如果使用量角器不存在元素,如何使测试失败
- c# - 如何在 C# 中逐行读取 CMD 输出结果
- java - Webflux Stream Large List 并使用另一个 springboot 应用程序使用它
- javascript - ActiveCampaign:获取表单提交的页面 URL