亚洲色蝴蝶中文娱乐网,在线亚洲欧美一区二区中文字幕,无人视频在线观看视频高清视频,99午夜国产精品一区二区,人人妻人人爽人人狠狠

PHP命名空間自動(dòng)加載實(shí)例

時(shí)間:2017-02-22 22:15:26 類型:PHP
字號(hào):    

通過(guò)PHP命名空間應(yīng)用, 自動(dòng)加載類, 是最近比較流行的應(yīng)用, 看個(gè)例子看看實(shí)際加載原理.

需知基礎(chǔ)知識(shí):PHP命名空間, spl_autoload_register魔法函數(shù)的作用

1.  Bird.php 文件代碼[通過(guò)命名空間被自動(dòng)加載的類文件]:

namespace app;
class Bird{
	public function song(){
		echo "開心的唱歌";
	}
}
2. index.php文件代碼[建立自動(dòng)加載機(jī)制函數(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é)果為 開心的唱歌