SPL spl_autoload_register 初体验

来源:互联网 发布:淘宝上做什么生意好做 编辑:程序博客网 时间:2024/06/04 19:07

        网上关于SPL spl_autoload_register的用法的例子有很多很多,自己也查看了很多,但感觉介绍得并不太详细,使自己真正能明白其中的原理苦闷了好一会儿。现将自己的理解记录下来。

 

       关于 Standard PHP Library (SPL) 的 autoload 的方法,这些都是 PHP 5.1.2 之后才加上的方法。为了方便,这里做了一些设定。假设你有类文件,放在/home/user/class/foo.class.php, 你当前的文件为/home/user/webroot/test.php, 示例代码如下。

 

在文件test.php中:

 

<?php

 

class autoload
{
  public static function load($classname)
  {

    $filename = "/home/user/class/".$classname."class.php";
    if (file_exists($filename)) {
      require_once $filename;
    }
  }
}
 
function __autoload($classname)
{
// 这个是默认的 autoload 方法

    $filename = "/home/user/class/".$classname."class.php";
    if (file_exists($filename)) {
      require_once $filename;
  }
}
 
// 注册一个 autoloader
spl_autoload_register('autoload::load');
/**
* __autoload 方法在 spl_autoload_register 后会失效,因为 autoload_func 函数指针已指向 spl_autoload 方法
* 可以通过下面的方法来把 _autoload 方法加入 autoload_functions list
*/
spl_autoload_register('__autoload');
 //注:下面的类看上去没有定义,但其实系统根据sql_autoload_register提供的路径会自动去/home/user///class/*.class.php下搜索foo.class.php文件,如果没找到才报错。
$foo = new foo();
$foo->bar();
?>

 

 

Reference to the URL:

http://hdwong.com/articles/2009/05/00000039.html

原创粉丝点击