Home  >  Article  >  php教程  >  [PHP] __autoload() magic method and spl_autoload_register

[PHP] __autoload() magic method and spl_autoload_register

WBOY
WBOYOriginal
2016-09-02 08:42:55930browse

Reference link:

1. Detailed explanation of the difference between spl_autoload_register and autoload

2. php.net automatic loading class

Many developers create a PHP source file for each class definition when writing object-oriented applications. A big annoyance is having to write a long list of include files (one file per class) at the beginning of each script.

In PHP 5, this is no longer necessary. You can define a __autoload() function that will be automatically called when trying to use a class that has not been defined yet. By calling this function, the scripting engine has a last chance to load the required classes before PHP fails with an error.

Simple introduction example:

First create a new class file MyClass.class.php:

<?php

class MyClass
{
    public function __construct()
    {
        echo "This is MyClass's construct";
    }

}

Create a new php file with any name in the same directory:

<?php

function __autoload($cls){
    var_dump($cls);
    require './'.$cls.".class.php";
}

$o1 = new MyClass();
// 这里不会再执行__autoload了,因为这个类已经require进来了。只有在当前文件中找不到该类的时候才会调用__autoload函数
$o2 = new MyClass();

Here the require content is placed in __autoload(). If this function is not defined, a fatal error (Fatal) will be reported, indicating that the MyClass class cannot be found.

When this magic method is defined When a new object is found and the class definition cannot be found in the current code (the above two conditions are met), the __autoload() function is passed in a class name parameter and the function is executed code snippet.

So, var_dump("MyClass"); and require './MyClass.class.php'; are executed in the function

The results are as follows:

string(7) "MyClass" This is MyClass's constructThis is MyClass's construct

The contents of one var_dump and the contents of two constructor echos are output here. It can be proved that when require comes in and new MyClass is created again, the __autoload() function will not be called again.

autoload has disadvantages: it cannot be defined repeatedly (a characteristic of the PHP language), which makes it inconvenient and prone to conflicts if team development is to be carried out.

So there is an autoload registration function spl_autoload_register after PHP 5.1.2. The following are some instructions for this function:

Register the function into the SPL __autoload function queue. Activate functions in this queue if they are not already active.

If you need multiple autoload functions, spl_autoload_register() meets such needs. It actually creates a queue of autoload functions and executes them one by one in the order they are defined. In contrast, __autoload() can only be defined once.

After the introduction of namespaces in PHP 5.3, the parameters of this function come in many forms:

spl_autoload_register('my_autoloader');    // my_autoloader是一个函数名

spl_autoload_register(array('Loader', 'loadClass'));  // 表示类内的静态方法,Loader::loadClass

// 或者,自 PHP 5.3.0 起可以使用一个匿名函数
spl_autoload_register(function ($class) {
    include 'classes/' . $class . '.class.php';
});

spl_autoload_register(__NAMESPACE__ .'\Foo::test'); // 自 PHP 5.3.0 起,可以使用命名空间的形式

This function only needs to be called before the new object.

The following is an example (testing the above 4 forms):

<?php

// namespace Atl;   // 加了这句话报错了!

function my_autoloader($cls){
    echo "<br/>$cls - my_autoloader <br/>";
    require_once './MyClass1.class.php';
}

class Loader{

    public static function loadClass($cls){
        echo "<br/>$cls - Loader::loadClass <br/>";
        require_once './MyClass2.class.php';
    }

    public static function nspClass($cls){
        echo "<br/>$cls - Loader::nspClass <br/>";
        require_once './MyClass3.class.php';
    }

}

spl_autoload_register('my_autoloader');

$o1 = new MyClass1();

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

$o2 = new MyClass2();

// 版本检测
if(version_compare(PHP_VERSION, '5.3.0', '<'))  die("以下的两个测试需要PHP 5.3及以上");

spl_autoload_register(__NAMESPACE__ .'\Loader::nspClass');
$o3 = new MyClass3();

spl_autoload_register(function ($cls) {
    echo "<br/>$cls - anonymous function <br/>";
    require_once './MyClass4.class.php';
});

$o4 = new MyClass4();

The output results are as follows (note that the search order is the same as the registration order):

MyClass1 - my_autoloader 
This is MyClass1's construct
MyClass2 - my_autoloader 

MyClass2 - Loader::loadClass 
This is MyClass2's construct
MyClass3 - my_autoloader 

MyClass3 - Loader::loadClass 

MyClass3 - Loader::nspClass 
This is MyClass3's construct
MyClass4 - my_autoloader 

MyClass4 - Loader::loadClass 

MyClass4 - Loader::nspClass 

MyClass4 - anonymous function 
This is MyClass4's construct

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
Previous article:Interface callNext article:Interface call