首页 » 网站建设 » phpsplregister技巧_小我整理超具体的 spl_autoload_register自动加载类终于不蒙圈了

phpsplregister技巧_小我整理超具体的 spl_autoload_register自动加载类终于不蒙圈了

访客 2024-12-08 0

扫一扫用手机浏览

文章目录 [+]

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

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

phpsplregister技巧_小我整理超具体的 spl_autoload_register自动加载类终于不蒙圈了

开始学习理解:

phpsplregister技巧_小我整理超具体的 spl_autoload_register自动加载类终于不蒙圈了
(图片来自网络侵删)

1.通过 127.0.0.1 根目录的url来访问 test/test.php 文件下的index方法,看我截图的步骤,文件的地址和构造

2.这个是index.php 方法 自动加载的核心文件,可根据文件自己考试测验操作

代码文件

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';

}

}

标签:

相关文章

大数据时代下的美股市场,机遇与挑战并存

随着信息技术的飞速发展,大数据已经成为各个行业的重要资源。在美国,大数据对美股市场的影响日益显著,既带来了前所未有的机遇,也带来了...

网站建设 2024-12-16 阅读0 评论0