zoukankan      html  css  js  c++  java
  • SPL spl_autoload_register与__autoload方法使用示例浅谈

    简介:这是SPL spl_autoload_register与__autoload方法使用示例浅谈的详细页面,介绍了和php,有关的知识、技巧、经验,和一些php源码等。

    class='pingjiaF' frameborder='0' src='http://biancheng.dnbcw.info/pingjia.php?id=339372' scrolling='no'>

    最近在写一个框架,当然过程中借鉴了很多前辈的写框架的经验啦,哈哈。

    在谈到框架自动加载类的方面,我大概翻了一下,现在主流的框架系统都使用spl_autoload_register函数,而非__autoload函数。

    额。。。为毛不用__autoload呢????

    功能强大点吧。。。合肥网产品中心

    示例:

    function my_own_loader($classname)
    {
        $class_file = strtolower($classname).".php";
        if (file_exists($class_file)){
            require_once($class_file);
        }
    }

    spl_autoload_register("my_own_loader");

    $a = new A();
     

    这里要注意的是:

    合肥网产品中心   http://lab.wehefei.com
    __autoload 方法在 spl_autoload_register 后会失效,因为 autoload_func 函数指针已指向 spl_autoload 方法
    * 可以通过下面的方法来把 _autoload 方法加入 autoload_functions list

    spl_autoload_register( '__autoload' );

    此外我们还可以使用我们自定义的加载方法:

    第一种函数式:

    function my_own_loader($classname)
    {
        $class_file = strtolower($classname).".php";
        if (file_exists($class_file)){
            require_once($class_file);
        }
    }

    spl_autoload_register("my_own_loader");

    $a = new A();
    合肥网产品中心   http://lab.wehefei.com

    第二种类式:
    class Loader
    {
        public static function my_own_loader($classname)
        {
            $class_file = strtolower($classname).".php";
            if (file_exists($class_file)){
                require_once($class_file);
            }
        }
    }

    // 通过数组的形式传递类和方法的名称
    spl_autoload_register(array("my_own_loader","Loader"));

    $a = new A();

    spl_autoload_register()函数应该是主流框架使用最多的也是非常核心的函数之一,可实现自动注册函数和类,实现类似__autoload() 函数功能,简化了类的调用与加载,提高了工作的效率。

    支持版本:PHP 5 >= 5.1.2

    至于效率问题。php手册上有如此之话:

    bool spl_autoload_register ([ callback $autoload_function ] )

    将函数注册到SPL __autoload函数栈中。如果该栈中的函数尚未激活,则激活它们。貌似他么指向同一个堆栈,效率上都是大哥二哥的问题,哈哈。。

    有兴趣的也可以具体去测试,下。。

    文章来源:合肥网产品中心  http://lab.wehefei.com/posts/286

    http://lab.wehefei.com/posts/311

    爱J2EE关注Java迈克尔杰克逊视频站JSON在线工具

    http://biancheng.dnbcw.info/php/339372.html pageNo:8
  • 相关阅读:
    C语言 · 选择排序
    C语言 · 生物芯片
    C语言 · 猜灯谜
    C语言 · x的x次幂结果为10
    C语言 · LOG大侠
    C语言 · 成绩查询系统
    C语言 · C++中map的用法详解
    C语言 · 方程的解
    斯坦福大学公开课:监督学习应用,梯度下降
    斯坦福大学公开课:机器学习的动机与应用
  • 原文地址:https://www.cnblogs.com/ooooo/p/2246172.html
Copyright © 2011-2022 走看看