dtt2012 2014-05-02 09:52
浏览 43
已采纳

在构造方法中启动另一个类?

I am looking into trying to simplify my PHP code some more, and I have yet to find an answer with this methodology one of my team members are using. Nor, have I ever saw this done before anywhere on the web.

Here is the code example from our web application which he is working on with me.

<?php

class ArticlesHandler {
   public function __construct() {
      require 'Articles.php';
      $articles = new Articles;
   } 
}

?>

Is this proper to init one class within another class?

For me, this just seems not proper standard to init classes to work together.

  • 写回答

4条回答 默认 最新

  • douhuan1648 2014-05-02 09:58
    关注

    Yes and no. It works, but this particular code can lead to a number of problems.

    1. You should be using require_once instead of require to avoid possible errors of including the same file twice. As it is this code here will bring your app to a complete stop:

      new ArticlesHandler;
      new ArticlesHandler;
      
    2. This creates a hard coupling to the Articles class. You should probably rather be using dependency injection and pass an instance of Article to the constructor of ArticlesHandler. See How Not To Kill Your Testability Using Statics.

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

报告相同问题?

悬赏问题

  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题
  • ¥15 有没有人能解决下这个问题吗,本人不会编程
  • ¥15 plotBAPC画图出错
  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗