views:

16

answers:

1

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  A: 

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)

Rudu
Thank you Rudi. So I don't need to require_once for the injection itself to work.
JDelage
In your above example you don't need any requires since `$storage` is just a variable - no definitino for `user.php` to need to understand. If you were using [type hinting][1] (an entirely different topic)... well then you would need to `require` the source that defines the type. [1]: http://php.net/manual/en/language.oop5.typehinting.php
Rudu