PHP include/require inside functions

2019-01-25 08:16发布

问题:

Having functions that are quite big and they are loading every time the page is loaded, would be better to write function foo(){ include(.../file_with_function's_code); return; } to minimize the size of the functions script? Or it doesn't matter because when a function is loaded (but not executed) also is loaded the content even if it is into an include? Thank you.

(Edit: my question is not about if it's possible or not)

回答1:

While @Luceos answer is technically correct (the best kind of correct), it does not answer the question you asked, namely is doing this better, or do includes happen regardless of function calls?

I tested this in the most basic way (OP, why didn't you?):

<?php
echo "Testing...";

function doThing() {
    include nonExistantFile.php;
}
//doThing();
echo "Done testing.";

Results:

if I call doThing(); I get a file not found warning.

If I comment out doThing();... there is no error! So you can save file load time by doing this.



回答2:

Or, as a good alternative, encapsulate your functions in classes, and take the benefit of __autoload :

function __autoload($class_name) {
    include $class_name . '.php';
}

Encapsulate myBigFunction() in a class

class myBigFunction {
  public static function run() {
    //the old code goes here
  }
}

save it as myBigFunction.php

When you call the function as static method on the class :

myBigFunction::run()

__autoload will load the file, but not before that.



回答3:

Yes that's possible; see http://www.php.net/manual/en/function.include.php

If the include occurs inside a function within the calling file, then all of the code contained in the called file will behave as though it had been defined inside that function. So, it will follow the variable scope of that function.

Question is, why not add the surrounding function definition to that included file. I think the only viable reason to include within a function is to split code within that function into bits.



回答4:

Both Luceos' and Albatrosz could be misread, so I felt that I should clarify these.

The include set of directives generate a runtime ZEND_INCLUDE_OR_EVAL operation which calls the Zend compiler to compile the referenced file. So in general you should not embed include statements in a function, as:

  • The include will be executed every time that code path is taken when the function is called. Compiling the same bit of code 100s of times is a bad idea.

  • If the code contains elements of global scope (e.g. function or class declarations) then executing that declaration even twice will cause compiler errors.

So don't unless you know what you are doing. Use techniques such are those described by Albatrosz. Incidentally his __autoload() function is just the sort of example of an exception where this is valid to do.