通过PHP命名空间应用, 自动加载类, 是最近比较流行的应用, 看个例子看看实际加载原理.
需知基础知识:PHP命名空间, spl_autoload_register魔法函数的作用
1. Bird.php 文件代码[通过命名空间被自动加载的类文件]:
namespace app;
class Bird{
public function song(){
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;
}
}
});
use app\Bird;
class Test{
public $bird;
public function __construct(){
$this->bird = new Bird(); //看这里, 这里竟然可以直接new Bird,还成功!!
}
}
$aa = new Test;
$aa->bird->song(); //显示结果为 开心的唱歌
