PHP 自动加载类

来源:互联网 发布:qq管家域名检测 编辑:程序博客网 时间:2024/05/17 23:47

__autoload

./myClass.php<?phpclass myClass {    public function __construct() {        echo "myClass init'ed successfuly!!!";    }}?>./index.php<?php// we've writen this code where we needfunction __autoload($classname) {    $filename = "./". $classname .".php";    include_once($filename);}// we've called a class ***$obj = new myClass();?>

spl_autoload_register

<?php    if(!function_exists('classAutoLoader')){        function classAutoLoader($class){            $class=strtolower($class);            $classFile=$_SERVER['DOCUMENT_ROOT'].'/include/class/'.$class.'.class.php';            if(is_file($classFile)&&!class_exists($class)) include $classFile;        }    }    spl_autoload_register('classAutoLoader');?>


加载类的2中方式:

方式一:

For example, let's say I have an app that has a base path defined as PATH_APP, and a simple structure with directories namedmodels,views and controllers. I often employ a naming structure whereby files are namedIndexView.php andIndexController.php inside the appropriate directory, and models generally have no particular scheme by default. I might have a loader function for this structure like this that gets registered withspl_autoload_register:

public function MVCLoader($class){    if (file_exists(PATH_APP.'/models/'.$class.'.php')) {        require_once(PATH_APP.'/models/'.$class.'.php');        return true;    }    else if (strpos($class,'View') !== false) {        if (file_exists(PATH_APP.'/views/'.$class.'.php')) {            require_once(PATH_APP.'/views/'.$class.'.php');            return true;        }    }    else if (strpos($class,'Controller') !== false) {        if (file_exists(PATH_APP.'/controllers/'.$class.'.php')) {            require_once(PATH_APP.'/controllers/'.$class.'.php');            return true;        }    }    return false;}



方式二:

public static function loadClass($class){    $files = array(        $class . '.php',        str_replace('_', '/', $class) . '.php',    );    foreach (explode(PATH_SEPARATOR, ini_get('include_path')) as $base_path)    {        foreach ($files as $file)        {            $path = "$base_path/$file";            if (file_exists($path) && is_readable($path))            {                include_once $path;                return;            }        }    }}


If I look for SomeClass_SeperatedWith_Underscores it will look for SomeClass_SeperatedWith_Underscores.php followed by SomeClass/SeperatedWith/Underscores.php rooted at each directory in the current include path.


0 0