PHP5中有一方法: __autoload() , 简单的说就是类的自动加载;

当你尝试使用一个PHP没有组织到的类, 它会寻找一个__autoload的全局函数. 如果存在这个函数,PHP会用一个参数来调用它,参数即类的名称。

那么简单测试一下。


首先建一个名为”Test_autoload.php”的文件:

  1. < ?php
  2. /**
  3. * 测试__autoload方法
  4. *
  5. */
  6. class Test_autoload {
  7.     public function __construct() {
  8.         echo "Test_autoload.";   
  9.     }
  10. }
  11. ?>

注意类名哦, 然后随便建个文件重写 __autoload() 方法,这里假设是”test.php”;

  1. < ?php
  2. /**
  3. * 重写 __autoload方法
  4. */
  5. function __autoload($class) {
  6.     include $class.'.php';
  7. }
  8.  
  9. $test = new Test_autoload();
  10. unset($test);
  11. ?>

最后结果为:Test_autoload. 很有趣吧,其实PHP5里还有很多更有趣的东西。记得以前python中用过的cPickle,可以把对象存入文件中,PHP5中也有对应的__sleep和__wakeup方法(叫做 “对象串行化”)。


文章标识
如果你是第一次来这儿,欢迎 订阅 这个博客。 第一时间看到更多精彩内容,谢谢你的访问!
本文固定链接: http://mifunny.info/autoload-of-php5-90.html
转载请注明出处及链接,非常感谢!
LD on 08月 26th, 2008 | File Under PHP | -