Blogger Information
Blog 25
fans 0
comment 0
visits 13650
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
php中类的自动加载实例演示
安超
Original
380 people have browsed it

类的自动加载

1.类的自动加载的两个条件:

a. 类名和文件名的相互对应(同名,类名采用大驼峰的原则,首字母大写);
b. 类空间和类文件路径的一致。

2.类的自动加载的一个关键函数;

splautoloadregister(function($class){
// 将空间名和文件路径协调起来
$path = str_replace(“\“,DIRECTORY_SEPARATOR,$class);
$file = __DIR
.’/‘ . $path.”.php”;
if(is_file($file) && file_exists($file)){
require $file;
}else{
die(“文件不存在”);
}
});

3. 类的别名的使用

use admin\controller\Index;
use admin\model\User;
use admin\view\index\Hello;

4.类的加载实例

4.1 文件架构

文件的架构如图:

4.2 要自动加载的文件

4.2.1 admin\controller下的Index.php
  1. <?php
  2. namespace admin\controller;
  3. class Index {
  4. public static function controllerhere()
  5. {
  6. echo __FILE__;
  7. }
  8. }
  9. ?>
4.2.2 admin\model下的User.php
  1. <?php
  2. namespace admin\model;
  3. class User{
  4. public static function userhere()
  5. {
  6. echo __FILE__;
  7. }
  8. }
  9. ?>
4.3 admin\view\index 下的Hello.php
  1. <?php
  2. namespace admin\view\index;
  3. class Hello{
  4. public static function hellohere()
  5. {
  6. echo __FILE__;
  7. }
  8. }
  9. ?>
4.4 用类封装后的加载文件index.php
  1. <?php
  2. namespace core;
  3. class Main {
  4. public function __construct()
  5. {
  6. }
  7. public static function show(){
  8. spl_autoload_register(function($class){
  9. echo $class;
  10. echo PHP_EOL;
  11. // 将空间名和文件路径协调起来
  12. $path = str_replace("\\",DIRECTORY_SEPARATOR,$class);
  13. $file = __DIR__ .'/' . $path.".php";
  14. if(is_file($file) && file_exists($file)){
  15. require $file;
  16. }else{
  17. die("文件不存在");
  18. }
  19. });
  20. }
  21. }
  22. Main::show();
  23. use admin\controller\Index;
  24. use admin\model\User;
  25. use admin\view\index\Hello;
  26. echo Index::controllerhere().PHP_EOL;
  27. echo User::userhere().PHP_EOL;
  28. echo Hello::hellohere().PHP_EOL;
  29. ?>
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!