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
You should be putting all your
requires andincludes 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:
user.phpandstorage.phpfrom other files (app.phpsay)user.phpand don’t want to worry about remembering to requirestorage.php.For #1 – you don’t need to worry about requires, however there’s no significant disadvantage to using
require_onceat the head of your PHP even if most of the time it’ll have already been required.For #2 – you need to use
require_onceat the header since you cannot useuser.phpwithoutstorage.phpand the final page only knows it needsuser.php.short answer: Use
require_onceto 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.phpthat usesuser.php, it shouldrequire_once 'user.php', but need not worry aboutstorage.phpsince it isn’t directly used, anduser.phpimplicitly includes it (that being said – no significant performance disadvantage of being thorough if you wish)