咱们说说php的自动加载类,这对于搞开发的兄弟比较重要。
当项目规模比较小的时候,咱们能够手动包含进来类定义文件或者直接定义而不包含。但是,若是咱们的项目比较大的时候,
就不得不一个一个的将大量类定义文件包含进来,不但麻烦,并且不美观,让人眼晕。这时咱们就能够用php的自动包含类定义文件的方法了。
先定义一个用于引用的类:
<?php
// test.class.php
class test {
public function __construct(){
print 'test class initialized!';
}
}
一、方法一:手动包含类
<?php
// index.php
define('ROOT',dirname(__FILE__));
require_once ROOT.'/test.class.php';
$t = new test();
二、方法二:使用函数__autoload实现自动加载类
在 PHP 5 中,再也不须要这样了。能够定义一个 __autoload 函数,它会在试图使用还没有被定义的类时自动调用。经过调用此函数,脚本引擎在 PHP 出错失败前有了最后一个机会加载所需的类。
<?php
// index.php
define('ROOT',dirname(__FILE__));
function __autoload($class_name){
$class_file = ROOT.'/'.$class_name.'.class.php';
if(file_exists($class_file)){
require_once $class_file;
}else{
print 'class: '.$class_file.' not found!';
}
}
$t = new test();
三、方法三:使用SPL函数spl_autoload_register
此函数在php版本>=5.1.0时可用
使用这个函数更方便,由于咱们能够自定义一个或多个自动加载类函数,而后使用spl_autoload_register函数注册咱们定义的函数了,以下:
<?php
// index.php
define('ROOT',dirname(__FILE__));
function my_autoload($class_name){
print 'my_autoload';
$class_file = ROOT.'/'.$class_name.'.class.php';
if(file_exists($class_file)){
require_once $class_file;
}else{
print 'class: '.$class_file.' not found!';
}
}
spl_autoload_register('my_autoload');
$t = new test();
注意:当咱们用函数spl_autoload_register注册咱们自定义的自动加载类函数后,原来的自动加载类函数
__autoload函数就无效了,除非也将其注册进来。
最后咱们说说set_include_path
咱们能够设置文件的默认包含路径,就不用在包含文件时加前面的目录了,
好比咱们设置 set_include_path(get_include_path().PATH_SEPARATOR.ROOT.'/database'),
这样咱们在包含文件时就写:include mysql.class.php就能够了,不用再写成这样了:
include ROOT.'/database/mysql.class.php'