When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.
知乎网友翻译如下: http://www.zhihu.com/people/damon-yang-15
1、被包含文件的变量的PHP include作用域遵从(不改变)包含文件所在处的作用域。
2、所有在被包含文件中定义的函数和类在被包含后,在包含文件里都具有全局作用域
下面三种方式效果完全一样,已亲测:
include_once 'bar.class.php';
class Foo
{
public static function DoIt()
{
new Bar();
}
}
vs
class Foo
{
public static function DoIt()
{
include_once 'bar.class.php';
new Bar();
}
}
vs
class Foo{
function load(){
include_once 'bar.class.php';
}
}
$foo = new Foo();
$foo => load();
$bar = new Bar();