PHP基础之Autoload_PHP教程

WBOY
发布: 2016-07-13 10:37:19
原创
1039 人浏览过

PHP的自动加载autoload机制很重要,这里做2个小练习

 
原创文章,转载请注明:http://www.cnblogs.com/phpgcs
 
文件结构如下,2种方式实现自动加载
 
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
  
 
首先看自定义函数方式:
 
    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());
?>
  运行结果如下:
 
+ View Code
  
 
 
 
第二种方式:
 
 
    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;
?>
  

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/735880.htmlTechArticlePHP的自动加载autoload机制很重要,这里做2个小练习 原创文章,转载请注明:http://www.cnblogs.com/phpgcs 文件结构如下,2种方式实现自动加载 1,...
相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!