PHP命名空间自动加载实例
通过PHP命名空间应用,自动加载类,是最近比较流行的应用,看个例子看看实际加载原理.
需知基础知识:PHP命名空间,spl_autoload_register魔法函数的作用
1.Bird.php文件代码[通过命名空间被自动加载的类文件]:
namespaceapp;
classBird{
publicfunctionsong(){
echo"开心的唱歌";
}
}
2.index.php文件代码[建立自动加载机制函数]
header("Content-Type:text/html;charset=UTF-8");
define("FILE_ROOT",dirname(__FILE__)."/");
spl_autoload_register(function($class){
if($class){
$file=FILE_ROOT.str_replace('\\','/',$class).".php";
if(file_exists($file)){
include $file;
}
}
});
useapp\Bird;
classTest{
public$bird;
publicfunction__construct(){
$this->bird=newBird();//看这里,这里竟然可以直接newBird,还成功!!
}
}
$aa=newTest;
$aa->bird->song();//显示结果为开心的唱歌