How to use include within a function?

The problem with using include() within a function is that:

include 'file1.php';

function include2() {
  include 'file2.php';
}

file1.php will have global scope. file2.php‘s scope is local to the function include2.

Now all functions are global in scope but variables are not. I’m not surprised this messes with include_once. If you really want to go this way—and honestly I wouldn’t—you may need to borrow an old C/C++ preprocessor trick:

if (!defined(FILE1_PHP)) {
  define(FILE1_PHP, true);

  // code here
}

If you want to go the way of lazy loading (which by the way can have opcode cache issues) use autoloading instead.

Leave a Comment