Alb*_*osz 15 php optimization function require include
拥有相当大的函数并且每次加载页面时加载它们都会更好地编写function foo(){ include(.../file_with_function's_code); return; }以最小化函数脚本的大小?或者无关紧要,因为当一个函数被加载(但没有执行)时,即使它被包含在内,也会加载内容?谢谢.
(编辑:我的问题不是关于它是否可能)
Dig*_*ris 22
虽然@Luceos答案在技术上是正确的(最好的正确),但它没有回答你问的问题,即更好地做到这一点,还是包括无论函数调用发生的事情?
我用最基本的方式测试了这个(OP,为什么不是你?):
<?php
echo "Testing...";
function doThing() {
include nonExistantFile.php;
}
//doThing();
echo "Done testing.";
Run Code Online (Sandbox Code Playgroud)
结果:
如果我打电话给doThing();我得到一个未找到文件的警告.
如果我评论出来doThing();......没有错误!这样你就可以节省文件加载时间.
dav*_*rad 11
或者,作为一个很好的替代方案,将您的函数封装在类中,并从以下方面获益__autoload:
function __autoload($class_name) {
include $class_name . '.php';
}
Run Code Online (Sandbox Code Playgroud)
封装myBigFunction()在一个类中
class myBigFunction {
public static function run() {
//the old code goes here
}
}
Run Code Online (Sandbox Code Playgroud)
保存为 myBigFunction.php
当您在类上调用该函数作为静态方法时:
myBigFunction::run()
Run Code Online (Sandbox Code Playgroud)
__autoload 将加载文件,但不是之前.
是的,这是可能的;见http://www.php.net/manual/en/function.include.php
如果包含发生在调用文件内的函数内,则被调用文件中包含的所有代码都将表现得好像它已在该函数内定义一样。因此,它将遵循该函数的变量范围。
问题是,为什么不将周围的函数定义添加到包含的文件中。我认为包含在函数中的唯一可行的原因是将该函数中的代码拆分为位。