spl_autoload_register函数详解

摘要:
函数__自动加载($class){$file=$class.'.class.php';$obj->

在了解这个函数之前先来看另一个函数:__autoload。  

一、__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()  

再看spl_autoload_register(),这个函数与__autoload有与曲同工之妙,看个简单的例子:  

  
 
<?
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();
?>

免责声明:文章转载自《spl_autoload_register函数详解》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇LUA交互函数GitHub:超分辨率最全资料集锦下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

vuex : 模块化改造

我们知道,vuex是vue技术栈中很重要的一部分,是一个很好用的状态管理库。 如果你的项目没有那么复杂,或者对vuex的使用没有那么重度,那么,是用不着modules功能的。 但如果你写着写着就发现你的vuex 代码过于臃肿,那么就可能需要modules功能来进行模块化改造了。 由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂...

FreeRTOS学习及移植笔记之二:在IAR和STM32F103VET上移植FreeRTOS

上一次,我们简单的测试了FreeRTOS的基于IAR EWARM v6.4和STM32F103VET6平台的Demo,对其有了一个基本认识。接下来我们开始自己移植FreeRTOS的过程。 1、创建一个“FreeRTOSTestProject”项目文件夹,并在其下创建FreeRTOS、Libraries、Project、User文件夹。 与无操作系统的项目...

8.nginx防DDOS

配置详解,查看链接:http://www.myhack58.com/Article/60/sort096/2015/59453.htm 配置文件: http {         #白名单         geo $whiteiplist  {         default 1;         192.168.0.225 0;         }  ...

使用PL/SQL Developer连接远程数据库

附送PL/SQL Developer11中文版下载地址 1、先到Oracle网站下载Instant Client : http://www.oracle.com/technetwork/database/features/instant-client/index-097480.html 根据你的操作系统选择不同的Instant Client版本 下载会是一...

module_init的加载和释放

  像你写C程序需要包含C库的头文件那样,Linux内核编程也需要包含Kernel头文件,大多的Linux驱动程序需要包含下面三个头文件:#include <linux/init.h>#include <linux/module.h>#include <linux/kernel.h>    其中,init.h 定义了驱...

在Visual C++ 中使用内联汇编 冷夜

一、 优点     使用内联汇编可以在 C/C++ 代码中嵌入汇编语言指令,而且不需要额外的汇编和连接步骤。在 Visual C++ 中,内联汇编是内置的编译器,因此不需要配置诸如 MASM 一类的独立汇编工具。这里,我们就以 Visual Studio .NET 2003 为背景,介绍在 Visual C++ 中使用内联汇的相关知识(如果是早期的版本,可...