Home >php教程 >php手册 >PHP class auto-loading mechanism

PHP class auto-loading mechanism

WBOY
WBOYOriginal
2016-09-19 08:54:591069browse

Auto loading of php:

Before PHP5, if we wanted to use a certain class or class method, it must include or require before it can be used. Every time we use a class, we need to write an include, which is troublesome

The php author wants to make it simple. It is best to reference a class. If there is no include currently, the system can automatically find the class and automatically introduce it~

So: the __autoload() function came into being.

Usually placed in the application entry class, such as discuz, placed in class_core.php.

Let’s talk about a simple example first:

The first situation: The content in file A.php is as follows

class A{

 public function __construct(){

   echo 'fff';

 }

}

?>

The content of the file C.php is as follows:

function __autoload($class)
{
$file = $class . '.php';
if (is_file($file)) {
require_once($file); a = new A(); //__autoload will be automatically called here and the A.php file will be introduced

?>

Second case:

Sometimes I want to customize autoload and give a cooler name for loader, so C.php should be changed to the following:

function loader($class){

$file = $class . '.php';

if (is_file($file)) {
require_once($file);
}
}

spl_autoload_register('loader'); //Register an automatic loading method, overwriting the original __autoload

$a = new A();

?>

The third situation

: I hope to be more advanced and use a class to manage automatic loading

class Loader {

public static function loadClass($class)

{
$file = $class . '.php';
if (is_file($file)) {
require_once($file);
}
}
}

spl_autoload_register(array('Loader', 'loadClass'));

$a = new A();

?>

Currently the best form.

Usually we put spl_autoload_register(*) in the entry script, that is, quoted from the beginning. For example, what discuz does below.

if(function_exist('spl_autoload_register')){

  spl_autoload_register(array('core','autoload')); //If it is php5 or above and there is a registration function, register the autoload in the core class you wrote as the automatic loading function

}else{

 function __autoload($class){ //If not, rewrite the PHP native function __autoload function and let it call its own core function.

  return core::autoload($class);

 }

}

It’s great to put this paragraph at the front of the entry file~

Reprint: http://www.cnblogs.com/zhongyuan/p/3583201.html

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