
test.php
<?php
function __autoload($class_name)
{
require_once $class_name . '.php';
}
$obj = new j();
?> 当前目录下有j.php
<?php
class j
{
function __construct()
{
echo "成功加载";
}
}
?>正常输出:成功加载
修改test.php代码
<?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 in F:\website\test.php on line 11
Fatal error: require_once() [function.require]: Failed opening required 'k.php' (include_path='.;C:\php5\pear') in F:\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 in F:\website\test.php on line 11
Fatal error: require_once() [function.require]: Failed opening required 'j.php' (include_path='.;C:\php5\pear') in F:\website\test.php on line 11
这个时候是因为找不到j.php
所以需要修改test.php代码
<?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()自动包含:
classname) { class_file = strtolower(classname).".php"; if (file_exists(
3.使用spl_autoload_register() 自定义的方法来加载文件 语法:bool spl_autoload_register ( [callback $autoload_function] )
classname) { class_file = strtolower(classname).".php"; if (file_exists(
$test = new Test();
也可以使用类的方法来实现自定义的加载函数
classname) { class_file = strtolower(classname).".php"; if (file_exists(
// 通过数组的形式传递类和方法,元素一为类名称、元素二为方法名称 // 方法为静态方法 spl_autoload_register(array("autoLoader","myLoader"));
$test = new Test();
本文由来源 21aspnet,由 javajgs_com 整理编辑,其版权均为 21aspnet 所有,文章内容系作者个人观点,不代表 Java架构师必看 对观点赞同或支持。如需转载,请注明文章来源。