php自动加载autoload机制示例分享
程序员文章站
2023-01-06 21:33:25
1,自定义函数
2,spl_autoload_register()
复制代码 代码如下:liuyuan@ebuinfo:/var/www/phpgcs/php_auto...
1,自定义函数
2,spl_autoload_register()
复制代码 代码如下:
liuyuan@ebuinfo:/var/www/phpgcs/php_autoload$ ll ./*
-rw-rw-r-- 1 liuyuan liuyuan 800 feb 19 11:39 ./func_autoload.php
-rw-rw-r-- 1 liuyuan liuyuan 906 feb 19 11:28 ./spl_autoload.php
./include:
total 16
drwxrwxr-x 2 liuyuan liuyuan 4096 feb 19 11:42 ./
drwxrwxr-x 3 liuyuan liuyuan 4096 feb 19 11:43 ../
-rw-rw-r-- 1 liuyuan liuyuan 142 feb 19 11:42 aclass.php
-rw-rw-r-- 1 liuyuan liuyuan 143 feb 19 11:42 bclass.php
首先看自定义函数方式:
复制代码 代码如下:
<?php
define('eol', (php_sapi == 'cli') ? php_eol : '</ br>');
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
array
(
[0] => /var/www/phpgcs/php_autoload/func_autoload.php
)
.:/usr/share/php:/usr/share/pear
aclass is loaded
bclass is loaded
array
(
[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
)
第二种方式:
复制代码 代码如下:
<?php
class myloader{
public static function autoload($classname){
$filename = './include/'.$classname.'.php';
if(file_exists($filename)){
include_once $filename;
}else{
exit('no file');
}
}
}
define('eol', (php_sapi == 'cli') ? php_eol : '<br />');
spl_autoload_register(array('myloader', 'autoload'));
/**
*__autoload 方法在 spl_autoload_register 后会失效,因为 autoload_func 函数指针已指向 spl_autoload 方法
* 可以通过下面的方法来把 _autoload 方法加入 autoload_functions list
*/
//spl_autoload_register( '__autoload' );
error_reporting(e_all^e_notice^e_warning^e_error);
error_reporting(e_notice | e_warning );
$a = new aclass();
print_r(get_included_files());
echo eol;
$b = new bclass();
echo eol;
?>
运行结果如下:
复制代码 代码如下:
liuyuan@ebuinfo:/var/www/phpgcs/php_autoload$ php spl_autoload.php
aclass is loaded
array
(
[0] => /var/www/phpgcs/php_autoload/spl_autoload.php
[1] => /var/www/phpgcs/php_autoload/include/aclass.php
)
bclass is loaded
上一篇: 怎么样轻松减肥?照三餐吃一样可以减肥
下一篇: 流鼻涕鼻塞怎么办?生姜红糖水治病又养颜