通過PHP命名空間應(yīng)用, 自動加載類, 是最近比較流行的應(yīng)用, 看個例子看看實際加載原理.
需知基礎(chǔ)知識:PHP命名空間, spl_autoload_register魔法函數(shù)的作用
1. Bird.php 文件代碼[通過命名空間被自動加載的類文件]:
namespace app; class Bird{ public function song(){ echo "開心的唱歌"; } }2. index.php文件代碼[建立自動加載機制函數(shù)]
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(); //顯示結(jié)果為 開心的唱歌