微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php自动加载autoload机制示例分享

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 : '');
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 : '
');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

原文地址:https://www.jb51.cc/php/25077.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐