博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
详解spl_autoload_register() 与 __autoload
阅读量:4560 次
发布时间:2019-06-08

本文共 1197 字,大约阅读时间需要 3 分钟。

一、__autoload 

这是一个自动加载函数,在PHP5中,当我们实例化一个未定义的类时,就会触发此函数。

printit.class.php 

 
<?php 
 
class PRINTIT { 
 
 function doPrint() {
  echo 'hello world';
 }
}
?> 
 
index.php 
 
<?
function __autoload( $class ) {
 $file $class '.class.php';  
 if is_file($file) ) {  
  require_once($file);  
 }
 
$obj new PRINTIT();
$obj->doPrint();

?>

运行index.php后正常输出hello world。在index.php中,由于没有包含printit.class.php,在实例化printit时,自动调用__autoload函数, 参数$class的值即为类名printit,此时printit.class.php就被引进来了。  

在面向对象中这种方法经常使用,可以避免书写过多的引用文件,同时也使整个系统更加灵活。

 

二、spl_autoload_register() 

<?

function loadprint( $class ) {
 $file $class '.class.php';  
 if (is_file($file)) {  
  require_once($file);  
 
 
spl_autoload_register( 'loadprint' ); 
 
$obj new PRINTIT();
$obj->doPrint();

?>

 

将__autoload换成loadprint函数。但是loadprint不会像__autoload自动触发,这时spl_autoload_register()就起作用了,它告诉PHP碰到没有定义的类就执行loadprint()。

spl_autoload_register() 调用静态方法

<? 

 
class test {
 public static function loadprint( $class ) {
  $file $class '.class.php';  
  if (is_file($file)) {  
   require_once($file);  
  
 }
 
spl_autoload_register(  array('test','loadprint')  );
//另一种写法:spl_autoload_register(  "test::loadprint"  ); 
 
$obj new PRINTIT();
$obj->doPrint();

?>

 

转载于:https://www.cnblogs.com/tudoux/p/5895726.html

你可能感兴趣的文章
SystemTap 静态探针安装包
查看>>
redis五种数据类型的使用
查看>>
浏览器全屏之requestFullScreen全屏与F11全屏
查看>>
软件包管理:rpm命令管理-安装升级与卸载
查看>>
旋转图像
查看>>
字符串中的数字(字符串、循环)
查看>>
15.select into
查看>>
运行web项目端口占用问题
查看>>
Java Spring-IOC和DI
查看>>
【NOIP1999】【Luogu1015】回文数(高精度,模拟)
查看>>
Linux上安装Python3.5
查看>>
crt安装
查看>>
git切换分支报错:error: pathspec 'origin/XXX' did not match any file(s) known to git
查看>>
c++中static的用法详解
查看>>
转 我修改的注册表,但是程序运行起来,还是记着以前的
查看>>
图片轮播功能
查看>>
第六周小组作业:软件测试和评估
查看>>
debian(kali Linux) 安装net Core
查看>>
centos 7防火墙设置
查看>>
自定义进度条(圆形、横向进度条)
查看>>