首页 > php面向对象 > php spl_autoload_register与__autoload方法详解

php spl_autoload_register与__autoload方法详解

php spl_autoload_register与__autoload方法详解

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

<?php
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();
?>

__autoload 方法在 spl_autoload_register 后会失效,因为 autoload_func 函数指针已指向 spl_autoload 方法

* 可以通过下面的方法来把 _autoload 方法加入 autoload_functions list

spl_autoload_register( '__autoload' );

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

第一种函数式:

<?php
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();
?>

第二种类式:class Loader

<?php
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://www.phprm.com/mxdx/fs3019.html

转载随意,但请附上文章地址:-)

标签:__autoload spl_autoload_register

相关文章

发表留言