php自动加载指定类,php自动加载类-凯发k8官方网
test.php 当前目录下有j.phpphp
test.php
function __autoload($class_name)
{
require_once $class_name . '.php';
}
$obj = new j();
?>
当前目录下有j.php
class j
{
function __construct()
{
echo "成功加载";
}
}
?>
正常输出:成功加载
修改test.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代码
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();
本文由来源 21aspnet,由 javajgs_com 整理编辑,其凯发k8官方网的版权均为 21aspnet 所有,文章内容系作者个人观点,不代表 java架构师必看 对观点赞同或支持。如需转载,请注明文章来源。
总结
以上是凯发k8官方网为你收集整理的的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇:
- 下一篇: