您的位置:首页 > 编程语言 > PHP开发

PHP自动加载类—__autoload()和spl_autoload_register() (补充)

2012-05-06 13:55 806 查看
test.php

[php]
view plaincopy

<?php
function __autoload($class_name)
{
require_once $class_name . '.php';
}
$obj = new j();

?>

当前目录下有j.php

[php]
view plaincopy

<?php
class j
{
function __construct()
{
echo "成功加载";
}
}
?>

正常输出:成功加载

修改test.php代码

[php]
view plaincopy

<?php
function __autoload($class_name)
{
require_once $class_name . '.php';
}
$obj = new k();
?>

运行test.php报错:

Warning: require_once(k.php) [function.require-once]: failed to open stream: No such file or directory inF:\website\test.php on line
11

Fatal error
: require_once() [function.require]: Failed opening required 'k.php' (include_path='.;C:\php5\pear') inF:\website\test.php on line
11

恢复test.php代码

但是将j.php移到另外目录k下,

运行test.php报错:

Warning: require_once(j.php) [function.require-once]: failed to open stream: No such file or directory inF:\website\test.php on line
11

Fatal error
: require_once() [function.require]: Failed opening required 'j.php' (include_path='.;C:\php5\pear') inF:\website\test.php on line
11

这个时候是因为找不到j.php

所以需要修改test.php代码

[php]
view plaincopy

<?php

function __autoload($class_name)
{
require_once "k/".$class_name . '.php';
}
$obj = new j();
?>

-----------------------------------------------------------------------------

为什么使用自动加载?



包含一般文件较少的情况会用手动包含要使用的类文件

当要包含大量类文件的时候,这样就会显得麻烦,就可以使用自动包含类。

类文件:test.php

class Test

{

public function __construct()

{

echo __CLASS__.__FUNCTION__;

}

}

1.手动包含:

require_once('test.php');

$test = new Test();

2.使用__autoload()自动包含:

// 这样实例化一个类的时候,将会自动包含同名的类文件

// 需要重载__autoload方法,自定义包含类文件的路径

function __autoload($classname)

{

$class_file = strtolower($classname).".php";

if (file_exists($class_file)){

require_once($class_file);

}

}

$test = new Test();

3.使用spl_autoload_register() 自定义的方法来加载文件

语法:bool spl_autoload_register ( [callback $autoload_function] )

function myLoader($classname)

{

$class_file = strtolower($classname).".php";

if (file_exists($class_file)){

require_once($class_file);

}

}

// 注册自定义方法

spl_autoload_register("myLoader");

$test = new Test();

也可以使用类的方法来实现自定义的加载函数

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();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: