方法1:
定义一个__autoload($className)函数接受一个参数
set_include_path(),是脚本里动态的对php.ini中的include_path进行修改
加载lib目录下的类
set_include_path(get_include_path().PATH_SEPARATOR."lib/");
//当前文件为03.php
class A
{
}
function __autoload($className) {
echo $className . '<br>';
include $className.'.php';
}
$t = new Test();
$a = new A();
/*
* 结果:
Test
根目录下的test类
*/
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();
/*
* 结果
* Test
根目录下的test类
Test1
lib目录下的test1类
.;C:\php\pear;lib/
*/
方法2:
使用spl_autoload_register()函数
此函数的功能就是把函数注册至SPL的__autoload函数栈中并移除系统默认的__autoload()函数
spl_autoload_register()可以调用多次,它实际上创建了autoload函数的队列,按定义的顺序逐个执行。而__autoload()只可以定义一次
新建文件04.php
function __autoload($className) {
echo '__autoload ' . $className . '<br>';
}
function __myautoload($className) {
echo '__myautoload ' . $className . '<br>';
}
spl_autoload_register('__myautoload');
$t = new Test();
/*
结果为:
此时__autoload()函数失效了
__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();
/*
结果为:
此时__myautoload()执行了两次
__myautoload Test
根目录下的test类
__myautoload Test1
lib目录下的test1类
*/
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();
/*
结果为:
__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类
*/