如何在php中对自动装载机制进行加载?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
1,自定义函数
2, spl_autoload_register ()
代码如下:
liuyuan@ebuinfo:/var/www/phpgcs/php_autoload $ ll。/*
-rw-rw-r - 1 liuyuan liuyuan 800年2月19日39。/func_autoload。php
-rw-rw-r - 1 liuyuan liuyuan 906年2月19日十一28。/spl_autoload.php
。总16/包括:
drwxrwxr-x 2 liuyuan liuyuan 4096年2月19日11:42。/
drwxrwxr-x 3 liuyuan liuyuan 4096年2月19日43 . ./
-rw-rw-r——1 liuyuan liuyuan 142年2月19日11:42 aClass。php
-rw-rw-r - 1 liuyuan liuyuan 143年2月19日11:42 bClass。php
首先看自定义函数方式:
代码如下:
& lt; ? php
,,,,定义(& # 39;eol # 39; (PHP_SAPI==& # 39; cli # 39;) ?PHP_EOL : '');
print_r(get_included_files());
echo EOL;
print get_include_path();
echo EOL;
//set_include_path(get_include_path().PATH_SEPARATOR.'/var/www/ly_php/php_spl/include/');
//set_include_path(dirname(__FILE__).'/include');
//set_include_path(dirname(__FILE__).'/include/');
function __autoload($className){
$filename='./include/'.$className.'.php';
//$filename='./include/'.$className.'.php';
//$filename='/var/www/ly_php/php_spl/include/'.$className.'.php';
if(file_exists($filename)){
include_once $filename;
}else{
exit('no file');
}
}
$a=new aClass();
$b=new bClass();
print_r(get_included_files());
?>
运行结果如下:
代码如下:
liuyuan@ebuinfo:/var/www/phpgcs/php_autoload$ php func_autoload.php数组
(
,,,,[0]=比;/var/www/phpgcs/php_autoload/func_autoload.php
。:/usr/share/php:/usr/share/梨
加载aClass
bClass加载阵列
(
,,,,[0]=比;/var/www/phpgcs/php_autoload/func_autoload.php
,,,,[1]=比;/var/www/phpgcs/php_autoload/include/aClass.php
,,,,[2]=比;/var/www/phpgcs/php_autoload/include/bClass.php
)
第二种方式:
代码如下:
& lt; ? php
,,,,类myLoader中{
,,,,,,,,公共静态函数自动装载($ className) {
,,,,,,,,,,,,文件名=& # 39;美元。/include/& # 39;。强生# 39;$ className。php # 39;;
,,,,,,,,,,,,如果(file_exists ($ filename)) {
,,,,,,,,,,,,,,,, include_once文件名美元;
,,,,,,,,,,,,}其他{
,,,,,,,,,,,,,,,,退出(& # 39;没有文件# 39;);
,,,,,,,,,,,,}
,,,,,,,,}
,,,,}
,,,,定义(& # 39;eol # 39; (PHP_SAPI==& # 39; cli # 39;) ?PHP_EOL: & # 39; & lt; br/祝辞& # 39;);
,,,, spl_autoload_register(数组(& # 39;myloader中# 39;& # 39;自动装载# 39;));
,,,,/* *
,,,, * __autoload方法在spl_autoload_register后会失效,因为autoload_func函数指针已指向spl_autoload方法
,,,, *可以通过下面的方法来把_autoload方法加入autoload_functions列表
,,,, */
,,,,//spl_autoload_register (& # 39; __autoload& # 39;);
,
,,,, error_reporting (E_ALL ^ E_NOTICE ^ E_WARNING ^ E_ERROR);
,,,, error_reporting (E_NOTICE |的E_WARNING);
,,,,一个美元=new aClass ();
,,,, print_r (get_included_files ());
,,,,回声EOL;
,,,, b=new bClass美元();
,,,,回声EOL;
?在
运行结果如下:
代码如下:
liuyuan@ebuinfo:/var/www/phpgcs/php_autoload php spl_autoload美元。php
aClass加载阵列
(
,,,,[0]=比;null