Search code examples
phpperformanceincludejit

PHP: where should I put my includes?


I have coded a set of basic functions I'm using in various scripts, but very seldom more than once in the same script.

Since I was schooled only in compiled languages programming I may not fully understand the dynamics of interpreted / JIT compiled languages: When using apache's PHP module, is each instruction compiled and then executed (like it happens in the CLI, for example), or is the whole script JIT compiled and then executed?

In case it's per instruction compiling/executing, should I have a block of require_once at the beginning of the file (which seems way more sane to me) or would it be more efficient to include them only if I need them (inside if blocks and so...)?


Solution

  • In the event that those included scripts are procedural, they are included inline, meaning that any variable definitions, executable code, etc are evaluated when the include happens. Of course, if it's a class, then you have access to that class from there on out. Some people opt to, in certain situations, use switches or if statements to decide whether or not to include a file that contains logic to be executed. It can be handy, or sloppy, depending on how it's used.

    If you're worried about memory usage because of includes, then using them in if blocks isn't a terrible thing, in my book, but that should be a very deliberate choice because you'll get a bunch of hard core OO guys getting on your case immediately over it shouting that it's bad design.

    I try to put all my includes at the top of a file unless it is a file that is completely superfluous and specific to a single usage.

    Hope that helps.