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

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

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.

图片转代码服务由CSDN问答提供 功能建议

我正在尝试更多地简化我的PHP代码,我还没有找到这种方法的答案 我的一个团队成员正在使用。 也没有,我曾经在网络上的任何地方看到过这种情况。

以下是我正在处理的Web应用程序的代码示例。 Articles> &lt;?php class ArticlesHandler { public function __construct(){ require'Fagess.php'; $ articles = new Articles; } } \ n?&gt;

在另一个类中初始化一个类是否合适?

对我来说,这似乎不是init类一起工作的正确标准。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

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条)

相关推荐 更多相似问题