Home  >  Article  >  php教程  >  php 类的自动加载机制

php 类的自动加载机制

WBOY
WBOYOriginal
2016-06-06 19:43:40983browse

类的自动加载,方便了引用过程,让类的初始化过程变的简单 spl_autoload_register($callback); 该函数的使用,会在new 的时候调用,并调用$callback回调函数来引用类文件, 所以有的时候会出现没有显式的引用文件,但可以正常地new 对象! 一种比较好的做法是

类的自动加载,方便了引用过程,让类的初始化过程变的简单

spl_autoload_register($callback);

该函数的使用,会在new 的时候调用,并调用$callback回调函数来引用类文件,

所以有的时候会出现没有显式的引用文件,但可以正常地new 对象!

一种比较好的做法是在初始化文件中写出回调函数和spl_autoload_register()函数

以此方便在后续的代码中new形成对象。

示例:

init.php

function callback($class) {  

  require $class . '.php';

}  

sql_autoload_register('callback');

---------------------------------------------

use.php

function init(){

  require 'init.php';

}

init();

$object = new new_object();

 

-----------------------------

new_object.php

class new_object{

  public function __construct() {

    echo 'autoload class';

  }

  public function __test() {

    echo 'do something here!';

  }

}

 

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn