PHP include/require inside functions

我怕爱的太早我们不能终老 提交于 2019-11-29 05:45:22

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.

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.

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.

TerryE

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!