duankuai6586 2010-09-09 17:15
浏览 32
已采纳

在PHP依赖注入中,我是否需要“require_once”定义依赖项的php文件?

Taking Fabien Potencier's example:

class User
{
  function __construct($storage)
  {
    $this->storage = $storage;
  }

  // ...
}

Assuming the Storage class is defined in a different php file (say, storage.php), do I need to include it in this file where the injection is done via a require_once?

Thanks,

JDelage

  • 写回答

1条回答 默认 最新

  • doushanlv5184 2010-09-09 17:36
    关注

    You should be putting all your requires and includes at the head of the file - that certainly a style thing, but for one thing it allows you to see by glancing at the source, what other files are need by your PHP file.

    There are two cases:

    1. You will only ever use user.php and storage.php from other files (app.php say)
    2. There are cases where you will use user.php and don't want to worry about remembering to require storage.php.

    For #1 - you don't need to worry about requires, however there's no significant disadvantage to using require_once at the head of your PHP even if most of the time it'll have already been required.

    For #2 - you need to use require_once at the header since you cannot use user.php without storage.php and the final page only knows it needs user.php.

    short answer: Use require_once to include all dependencies for the code (to allow it to easily be used by other code)

    note: You should only include direct-dependencies for the code. That is: if you have group.php that uses user.php, it should require_once 'user.php', but need not worry about storage.php since it isn't directly used, and user.php implicitly includes it (that being said - no significant performance disadvantage of being thorough if you wish)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line