方法1:
定義一個__autoload($className)函數(shù)接受一個參數(shù)
set_include_path(),是腳本里動態(tài)的對php.ini中的include_path進行修改
加載lib目錄下的類
set_include_path(get_include_path().PATH_SEPARATOR."lib/");

image.png
//當前文件為03.php
class A
{
}
function __autoload($className) {
echo $className . '<br>';
include $className.'.php';
}
$t = new Test();
$a = new A();
/*
* 結(jié)果:
Test
根目錄下的test類
*/

image.png
set_include_path(get_include_path() . PATH_SEPARATOR .'lib/');
function __autoload($className) {
echo $className . '<br>';
include $className.'.php';
}
$t = new Test();
$t = new Test1();
echo get_include_path();
/*
* 結(jié)果
* Test
根目錄下的test類
Test1
lib目錄下的test1類
.;C:\php\pear;lib/
*/
方法2:
使用spl_autoload_register()函數(shù)
此函數(shù)的功能就是把函數(shù)注冊至SPL的__autoload函數(shù)棧中并移除系統(tǒng)默認的__autoload()函數(shù)
spl_autoload_register()可以調(diào)用多次,它實際上創(chuàng)建了autoload函數(shù)的隊列,按定義的順序逐個執(zhí)行。而__autoload()只可以定義一次
新建文件04.php
function __autoload($className) {
echo '__autoload ' . $className . '<br>';
}
function __myautoload($className) {
echo '__myautoload ' . $className . '<br>';
}
spl_autoload_register('__myautoload');
$t = new Test();
/*
結(jié)果為:
此時__autoload()函數(shù)失效了
__myautoload Test
Fatal error: Uncaught Error: Class 'Test' not found in D:\Web\test\18-11-10\04.php:13 Stack trace: #0 {main} thrown in D:\Web\test\18-11-10\04.php on line 13
*/
set_include_path(get_include_path() . PATH_SEPARATOR .'lib/');
function __autoload($className) {
echo '__autoload ' . $className . '<br>';
}
function __myautoload($className) {
echo '__myautoload ' . $className . '<br>';
include $className.'.php';
}
spl_autoload_register('__myautoload');
new Test();
new Test1();
/*
結(jié)果為:
此時__myautoload()執(zhí)行了兩次
__myautoload Test
根目錄下的test類
__myautoload Test1
lib目錄下的test1類
*/

image.png
set_include_path(get_include_path() . PATH_SEPARATOR .'lib/');
function __autoload($className) {
echo '__autoload ' . $className . '<br>';
include 'lib1/' . $className.'.php';
}
function __myautoload($className) {
echo '__myautoload ' . $className . '<br>';
include $className.'.php';
}
spl_autoload_register('__myautoload');
spl_autoload_register('__autoload');
// new Test();
// new Test1();
new T();
/*
結(jié)果為:
__myautoload T
Warning: include(T.php): failed to open stream: No such file or directory in D:\Web\test\18-11-10\04.php on line 12
Warning: include(): Failed opening 'T.php' for inclusion (include_path='.;C:\php\pear;lib/') in D:\Web\test\18-11-10\04.php on line 12
__autoload T
lib1目錄下的T類
*/
set_include_path(get_include_path() . PATH_SEPARATOR .'lib/');
class AutoLoad
{
public static function loadClass($className) {
echo 'AutoLoad 中的 loadClass ' . $className . '<br>';
include $className . '.php';
}
}
spl_autoload_register(['AutoLoad','loadClass']);
new Test();
new Test1();
/*
AutoLoad 中的 loadClass Test
根目錄下的test類
AutoLoad 中的 loadClass Test1
lib目錄下的test1類
*/