采用spl_autoload实现自动加载的一点心得,适合新手参考。
项目名为webServer,项目目录结构大致为
controlers文件夹
-------Todo.php
index.php
假设Todo.php中存在一个类,名为Todo,在index.php中进行实例化new Todo();
那么我们在index.php中添加以下代码
function controllers_autoload($class) {
set_include_path(__DIR__."/controllers/");
spl_autoload_extensions('.php');
spl_autoload($class);
}
spl_autoload_register('controllers_autoload');
set_include_path设置引用php文件的路径,一般情况下我们取环境变量(用get_include_path,获取的路径取决于php.ini中的include_path),为了方便明白自动加载的实现,我们这里用最笨的方法取得物理路径(注意是物理路径,不是访问路径)
spl_autoload_extensions说明引用的文件类型,参数可以是".php",".ini"等等
spl_autoload最后用__autoload的默认实现,来自动加载
spl_autoload_register方法将自动加载的方法放入栈中,我们可以用多个register来加载不同路径下的不同文件