Reputation: 40140
Do you position all of your include_once
and require_once
at the start of the file, so it's clear what it's dependencies are, or do you put them at the most local scope where they are used, for efficiency?
Let's say I have an error handling file which has a function to display an error message - would you ...
require_once('error_handling.php');
... lots of code ...
if ($should_be_true === False)
{
ReportErrror(); // declared in error_handling.php
}
or do you
... lots of code ...
if ($should_be_true === False)
{
require_once('error_handling.php');
ReportErrror(); // declared in error_handling.php
}
hmm, looks like they deleted the best-practise
tag, along with subjective
in the great tag purge of '10
Upvotes: 4
Views: 1363
Reputation: 85794
Meh. Totally dependent on the situation.
If it's a small include and you're going to use it in 95% of situations, top is fine. Top really is fine for almost all cases.
But if it's an absolutely huge library to, say, parse something that will only come up in 5% of requests, require when needed. It might be worth making a comment at the top to make the dependency known, however—happy medium?
Anyway. It's a judgment call every time. Best not worry too much about the performance issue for the uncertain cases until milliseconds of performance actually become an issue for you. (And wouldn't that sort of popularity be an excellent issue to have?)
Upvotes: 1
Reputation: 163228
I'd most definitely go with the second example, because to load in stuff that potentially wouldn't be used is just evil.
Upvotes: 2
Reputation: 77722
This is probably a matter of taste for the most part.
In C/C++ style, I always put them on top, so - as you mentioned - the dependencies are immediately clear. Also, it gives you the option to rearrange the order of inclusion (which should normally never matter).
Now, since this is a runtime affair (unlike C/C++), it would make sense to postpone including huge files that are rarely ever needed.
It's a matter of balance - cleaner code (IMHO) vs performance. I would tend towards cleaner code, unless you have a PHP file that is a) called a lot, b) uses a huge PHP file that is c) almost never needed.
Upvotes: 2