__autoload和spl_autoload_register()

来源:互联网 发布:omega7 知乎 编辑:程序博客网 时间:2024/05/19 17:56
  1. __autoload()函数  
  2.   
  3. test.php  
  4. <?php  
  5. function __autoload( $class ) {  
  6.  $file = $class . '.class.php';    
  7.  if ( is_file($file) ) {    
  8.   require_once($file);    
  9.  }  
  10. }   
  11.    
  12. $obj = new test();  
  13. $obj->index();  
  14. ?>  
  15.   
  16. test.class.php  
  17. <?php  
  18.     class test{  
  19.   
  20.         function index(){  
  21.   
  22.             echo 'test.class.php的test类的index方法被调用';  
  23.         }  
  24.     }  
  25. ?>  
  26.   
  27. 在面向对象中这种方法经常使用,可以避免书写过多的引用文件,同时也使整个系统更加灵活。  
  28.   
  29. spl_autoload_register()函数  
  30. <?php  
  31. function example( $class ) {  
  32.  $file = $class . '.class.php';    
  33.  if ( is_file($file) ) {    
  34.   require_once($file);    
  35.  }  
  36. }   
  37.    
  38.   
  39. spl_autoload_register( 'example' );   
  40. $obj = new test();  
  41. $obj->index();  
  42. ?>  
  43. example不会像__autoload自动触发,spl_autoload_register()就起作用了,它告诉PHP碰到没有定义的类就执行example()。  
  44.   
  45. 静态方法的例子  
  46.   
  47. <?php  
  48.   
  49. class StaticTest{  
  50.       
  51.     static public function example( $class ) {  
  52.      $file = $class . '.class.php';    
  53.      if ( is_file($file) ) {    
  54.       require_once($file);    
  55.      }  
  56.     }   
  57.        
  58. }  
  59. spl_autoload_register(array('StaticTest','example'));   
  60. //spl_autoload_register('StaticTest::example');   
  61. $obj = new test();  
  62. $obj->index();  
  63. ?>  
阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 人参五味子颗粒 洋参片 西洋参什么价格 参芪降糖 参芍片 参术儿康糖浆 人参膏 参须的功效与作用 金虫草三参多少钱 龙参草 松参养心胶囊 吉福参牌人参滴丸 虫草地参 太极参 吉林参 边条参 参与商 参与 动如参与商 参与读音 参与的读音 重在参与 参与英文 参与拼音 参与的英文 参与的拼音 参与 英文 参与英语 参与的意思 重在参与什么意思 西洋参与人参有何区别 综过客参与者 综剧过客和参与者 干海参与鲜海参 梦见自己参与枪战 干海参与鲜海参区别 参与英语怎么说 武汉2019军运会参与国 此生不相见动如参与商 扪参历井仰胁息 扪参历井