php自动加载指定类,PHP自动加载类-Java架构师必看
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 整理编辑,其版权均为 21aspnet 所有,文章内容系作者个人观点,不代表 Java架构师必看 对观点赞同或支持。如需转载,请注明文章来源。
总结
以上是生活随笔为你收集整理的php自动加载指定类,PHP自动加载类-Java架构师必看的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 重装php后网站无法,1、解决重装php
- 下一篇: axure怎么转换成php,墨刀和axu