PHP中类的自动加载的方法

2025-05-29 0 26

自动加载是指,在外面的页面中,并不需要去“引入”文件,但是程序会在需要的时候动态加载需要的文件。

方法1:使用__autoload魔术函数

当程序需要某个时,就会去调用该函数,该函数我们需要自己去定义并在其中写好加载文件的通用语句。

?

1

2

3

4

5

6

7

8

9
<?php

//需要类是自动调用,而且会传进来一个类名,这个案例的文件名为21A.class.php,类名为A

function __autoload($className){

require "./21".$className.".class.php";

}

$o1 = new A();

$o1->v1 = 10;

echo "<br/>v1:".$o1->v1;

?>

方法2:使用spl_autoload_register函数

该函数的作用是生命多个可以用来代替autoload函数作用的函数,语法如下:spl_autoload_regist("函数名1");如果用spl_autoload_register,autoload就失效了。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18
<?php

//注册两个用于自动加载的函数名

spl_autoload_register('auto1');

spl_autoload_register('auto2');

function auto1($className){

$file = "./21".$className.".class.php";

if(file_exists($file)){

require "./21".$className.".class.php";

}

}

function auto1($className){

$file = "./22".$className.".class.php";

if(file_exists($file)){

require "./22".$className.".class.php";

}

}

//如果需要一个雷,但这个页面还没有记载,就会依次调用auto1和auto2,知道找到该类文件并加载

?>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。

原文链接:http://www.jianshu.com/p/42db1a8c3c06

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 PHP中类的自动加载的方法 https://www.kuaiidc.com/95092.html

相关文章

发表评论
暂无评论