[b]包含一般文件较少的情况会用手动包含要使用的类文件
当要包含大量类文件的时候,这样就会显得麻烦,就可以使用自动包含类。[/b]
类文件:test.php
[b]1.手动包含:[/b]
[b]2.使用__autoload()自动包含:[/b]
[b]3.使用spl_autoload_register() 自定义的方法来加载文件
[color=blue]语法[/color]:bool [color=red]spl_autoload_register [/color]( [callback $autoload_function] )[/b]
[b]也可以使用类的方法来实现自定义的加载函数[/b]
当要包含大量类文件的时候,这样就会显得麻烦,就可以使用自动包含类。[/b]
类文件:test.php
class Test
{
public function __construct()
{
echo __CLASS__.__FUNCTION__;
}
}
[b]1.手动包含:[/b]
require_once('test.php');
$test = new Test();
[b]2.使用__autoload()自动包含:[/b]
// 这样实例化一个类的时候,将会自动包含同名的类文件
// 需要重载__autoload方法,自定义包含类文件的路径
function __autoload($classname)
{
$class_file = strtolower($classname).".php";
if (file_exists($class_file)){
require_once($class_file);
}
}
$test = new Test();
[b]3.使用spl_autoload_register() 自定义的方法来加载文件
[color=blue]语法[/color]:bool [color=red]spl_autoload_register [/color]( [callback $autoload_function] )[/b]
function myLoader($classname)
{
$class_file = strtolower($classname).".php";
if (file_exists($class_file)){
require_once($class_file);
}
}
// 注册自定义方法
spl_autoload_register("myLoader");
$test = new Test();
[b]也可以使用类的方法来实现自定义的加载函数[/b]
class autoLoader
{
public static function myLoader($classname)
{
$class_file = strtolower($classname).".php";
if (file_exists($class_file)){
require_once($class_file);
}
}
}
// 通过数组的形式传递类和方法,元素一为类名称、元素二为方法名称
// 方法为静态方法
spl_autoload_register(array("autoLoader","myLoader"));
$test = new Test();