tags:

views:

132

answers:

2

Hi all,

I am needing some information on including files in PHP classes. E.G.

include Foo2.php; //<--- Is this good?    
class Foo {
      function doFoo(){
         include("Foo2.php"); //<--- or is this better?
         //do something with vars from Foo2
      }
}

I was wondering what the differences were beside scope and if there were any other ways to include another php file in a class.

Thanks in advance for any responses.

+4  A: 

include at the global scope. It's much readable and maintainable.

erenon
Although this is true, if I am including many files in a global scope that might not get used wouldn't it be inefficient?I suppose these are micro efficiencies and don't really matter?
Mozez
Use bytecode cache, e.g: APC, Zend Optimizer, and it won't be a problem.
erenon
That's the tradeoff I've found: include at the top - easy to find and more likely to easily find errors during refactoring (because you don't have to execute different code paths to make sure something's included) OR include within function (or even inside an "if") and then you only have to include the file if you need it -- and you've localized (cohesion) stuff that goes together.
grantwparks
A: 

You can only include PHP files in the functions of a class, or outside the class completely, so you have both of the ways down.

The difference of those is that the one inside the function will only be included if you call that function.

I find that the one inside of the function is better, because then it won't be included automatically, and you can only include it if you need a function inside that class, which can be really helpful if you deal with a LOT of files.

Chacha102