在开发大型项目的时候,引入文件是非常多的,
为了防止文件重名我们会定义命名空间,命名空间使用namespace定义。
为了代码的高度复用,我们会采用文件引入的形式,比如说使用 require、include 引入。
项目越来越大,那么使用的require 会越来越多,有没有一种办法可以自动引入类库呢?
应着这样的需求,__autoload 函数 和 spl_autoload_register 函数就出现了。
现在就来看看是如何引入的:
分两种情况:
1、spl_auload_register
#init.php namespace desgin\celue2; class Init{ public static function _autoload($class){ $file=ROOT_PATH."/".str_replace("\\","/",$class).".php"; if(is_file($file)){ require_once $file; } } } #index.php namespace desgin\celue2; define("ROOT_PATH",dirname(dirname(dirname(__FILE__)))); //引入 init.php include_once "init.php"; //自动引入加载类 spl_autoload_register('\desgin\celue2\Init::_autoload'); #\desgin\celue2\Init::_autoload 切记没有括号 和参数类 class Index{ protected $strategy; public function view(){ $this->strateg->ad(); $this->strateg->love(); } public function set(Strategy $strategy){ $this->strateg=$strategy; } } $Index=new Index(); if(isset($_GET['t']) && $_GET['t']=="female"){ $Index->set(new Female()); }else{ $Index->set(new Man()); } $Index->view();
2、__autoload
//首先判断类是否存在,如果存在就引入. function __autoload($class){ if(file_exists($class.".php")){ include_once $class.".php"; } }
两种定义方式都是自动引入文件,那么两者有什么区别?
1、__autoload 在整个项目中只能定义一个函数方法
2、spl_autoload_register() 允许在同一个项目中定义多个方法,引入不同文件下的文件。
在现在这个项目中,经常会使用 composer 工具 拉取一些代码,都会自动引入自己的类库,这样就能显现出spl_autoload_register 的优势了。