Blogger Information
Blog 43
fans 4
comment 0
visits 19268
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP类的自动加载器
汇享科技
Original
322 people have browsed it

类的自动加载器

  • 使用spl_autoload_register进行创建加载器

  • 自动加载器文件autoloader.php

  1. <?php
  2. //自动加载器
  3. // spl_autoload_register
  4. spl_autoload_register(function($class){
  5. $p = str_replace('\\',DIRECTORY_SEPARATOR,$class);
  6. require __DIR__ . DIRECTORY_SEPARATOR . $p . '.php';
  7. });
  • Demo1.php
  1. <?php
  2. namespace admin\controller;
  3. class Demo1
  4. {
  5. public static function f1()
  6. {
  7. return __CLASS__ .'下的方法'. __METHOD__;
  8. }
  9. public static function getUser($name){
  10. return '我是'.$name;
  11. }
  12. }
  • Demo2.php
  1. <?php
  2. namespace admin\controller;
  3. class Demo2
  4. {
  5. public static function f2()
  6. {
  7. return __CLASS__ . '下的方法'.__METHOD__;
  8. }
  9. public static function getUser($name){
  10. return '我是'.$name;
  11. }
  12. }
  • 入口文件index.php
  1. <?php
  2. //引入加载器
  3. require './autoloader.php';
  4. //起别名
  5. use admin\controller\Demo1;
  6. use admin\controller\Demo2;
  7. //调用加载器方法
  8. echo Demo1::f1().'<hr>';
  9. echo Demo1::getUser('Demo1').'<hr>';
  10. echo Demo2::f2().'<hr>';
  11. echo Demo2::getUser('Demo2').'<hr>';
  • 运行结果
    08548-117od9za5yz.png
Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!