领先的免费Web技术教程,涵盖HTML到ASP.NET

网站首页 > 知识剖析 正文

个人整理超详细的 spl_autoload_register自动加载类终于不蒙圈了

nixiaole 2024-11-14 18:34:12 知识剖析 19 ℃

前言:

以前百度过很多关于spl_autoload_register 自动加载类的实现方法,但内容都不尽人意,完全无法达到自动加载类的理解,以至于看完整个文章都是蒙圈的。于是自己整理了一份简单清晰的spl_autoload_register自动加载的代码,让对spl_autoload_register逻辑或者自动加载类不清楚的初学者可以有效参考学习,代码简单,结构清晰,理解容易,另外把放到链接里面可下载了自己理解,如果不懂或者喜欢的可以一起交流学习,后续不定时会发一些其他功能

[链接地址:https://note.youdao.com/s/UrsNcYnD]

开始学习理解:




代码文件

index.php

<?php

//自动加载方法 这个方法是spl_autoload_register 调用的 $classname的变量系统自动检测new 的值,不用手动赋值变量[非私用学习不可转载盗用]

function loadclass($classname){

//1.获取new 的地址 例如:new \test\test();则会得到$classname=\test\test[非私用学习不可转载盗用]

//2把\test\test 通过explode 转成 array('test','test');格式[非私用学习不可转载盗用]

$path=explode('\\',$classname);

foreach($path as $k=>$v){

//如果存在空的数组就删除[非私用学习不可转载盗用]

if(!$v){

unset($path[$k]);

}

}

//3.把array('test','test') implode字符串 test/test.php 的文件地址[非私用学习不可转载盗用]

$path=implode($path,'/');

$url=$path.'.php';

//4.检查文件是否存在,不存在则报错,存在则加载文件[非私用学习不可转载盗用]

if(file_exists($url)){

require_once($url);

}else{

echo 'error';

}

}

//1.获取url的链接地址 例如:http://127.0.0.1/index.php/test/test1/index 然后获取 /test/test1/index ,通过explode 转数组array('test','test','index')

//[非私用学习不可转载盗用]

$path=explode('/',$_SERVER['PATH_INFO']);

//2.检测是否存在空的值,存在则删除[非私用学习不可转载盗用]

foreach($path as $k=>$v){

if(!$v){

unset($path[$k]);

}

}

//2. array_pop获取数组 array('test','test','index') 的最后一个值 index 这个就是class对应的方法[非私用学习不可转载盗用]

$function=array_pop($path);

//3. array('test','test','index') implode 转字符 \test\test[非私用学习不可转载盗用]

$path='\\'.implode($path,'\\');

//4. spl_autoload_register 方法自动调用 设置的 loadclass 方法[非私用学习不可转载盗用]

spl_autoload_register("loadclass");

//5 加载 $class=new \test\test(); , spl_autoload_register会自动检测 \test\test[非私用学习不可转载盗用]

$class=new $path();

//6. $class->index(); 调用 test/test.php 文件下面的 test类中的 index方法,至此成功[非私用学习不可转载盗用]

$class->$function();

die;

//提示:可以看看我test.php 文件是如果调用多个文件的方法的[非私用学习不可转载盗用]


test.php

<?php

namespace test;

use \test\test1;

use \test\server;

class test{


public function index(){


echo 'test-index';

echo PHP_EOL;

$test1 = new test1();

$test1->index();

echo PHP_EOL;

$test1 = new server();

$test1->index();

}


}


test1.php

<?php

namespace test;

use \test\server;

class test1{


public function index(){


echo 'test1-index';

echo PHP_EOL;

$test1 = new server();

$test1->index();

}


}


server.php

<?php

namespace test;

class server{


public function index(){


echo 'service-index';


}


}

Tags:

最近发表
标签列表