views:

98

answers:

2

Where should I put require_once statements, and why?

  1. Always on the beginning of a file, before the class,
  2. In the actual method when the file is really needed
  3. It depends
  4. ?

Most frameworks put includes at the beginning and do not care if the file is really needed.
Using autoloader is the other case here.

Edit:

Surely, we all agree, that the autoloader is the way to go. But that is the 'other case' I was not asking here. (BTW, Zend Framework Application uses autoloader, and the files are still hard-required, and placed at the beginning).

I just wanted to know, why do programmers include required files at the beginning of the file, even when they likely will not be used at all (e.g. Exception files).

+3  A: 

I'd say 3. It depends. If you're dealing with a lot of code, it may be worth loading the include file on request only, as loading code will take time to do, and eat up memory. On the other hand, this makes maintenance much harder, especially if you have dependencies. If you load includes "on demand", you may want to use a wrapper function so you can keep track of what module is loaded where.

I think the autoloader mechanism really is the way to go - of course, the application's design needs to be heavily object oriented for that to work.

Pekka
+5  A: 

Autoloading is a much better practice, as it will only load what is needed. Obviously, you also need to include the file which defines the __autoload function, so you're going to have some somewhere.

I usually have a single file called "includes.php" which then defines the __autoload and includes all the non-class files (such as function libraries, configuration files, etc). This file is loaded at the start of each page.

nickf
+1 autoloading is faster for large codebases using an opcode cache
Andy
@andy: really? surely if you're using an opcode cache you may as well just load the whole lot on every request?
Tom Haigh
- in that the overhead of parsing the script is gone, and therefore going through _autoload everytime may take longer? I guess you still have the compiled code in memory though if you load everything.
Tom Haigh
@Tom autoloading is faster for my large codebase, and opcode caching speeds it up :)
Andy
@Andy: Thanks, I just wonder whether if you were to combine your entire library into one file (e.g. as a build step), and use opcode caching as well, whether that could be even faster, as a) including it all shouldn't be an issue because it is cached, and b) you are not calling _autoload() everytime you use a class for the first time. But I have no data to back this up so your approach is probably best
Tom Haigh
@Tom hmm an interesting question, I would imagine that our memory footprint (106k lines of includes) would make it infeasible but it's certainly an intriguing thought. I'll report back if I get round to testing it!
Andy