开发者

In PHP Dependency Injection, do I need to "require_once" the php file where the dependency is defined?

Taking Fabien Potencier's example:

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

  // ...
}

Assuming the开发者_C百科 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


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜