Home  >  Article  >  Backend Development  >  Note 019 Automatic loading through spl_autoload_register

Note 019 Automatic loading through spl_autoload_register

黄舟
黄舟Original
2016-12-26 10:13:351121browse

spl_autoload_register

(PHP 5 >= 5.1.2, PHP 7)

spl_autoload_register — Register the given function as an implementation of __autoload

Syntax

bool spl_autoload_register ([ callable $autoload_function [, bool $throw = true [, bool $prepend = false ]]] )

Description

Through this function, you can set the loaded class Specify the addressing mode so you don’t need to require and include in bulk. The system will automatically follow the specified rules and go to the corresponding location to find the class that needs to be instantiated. Although this method is relatively low-level, if there is a framework, we generally do not need to do this work. But it is inevitable that there will still be times when I need to use it. For example, when I was writing this blog, I needed to mess with the script myself. At this time, there is no way around it. The following example is a simple autoloading program to be used in my script.

Example

spl_autoload_register(function ($class) {
    $rootPath = realpath(sprintf('%s/..', __DIR__));
    $paths = array(        'src',
    );    foreach ($paths as $path) {        if (is_file(
            $file = $rootPath . DIRECTORY_SEPARATOR . $path . DIRECTORY_SEPARATOR . $class
            . '.php'
        )) {            include $file;            break;
        }
    }
});

Note that anonymous functions can only be used in PHP 5.3 and above. If you find that it cannot be used, check your PHP version. Here I simply specify all classes to search in my src folder, and the class names are exactly the same as the file names.

The above is the content of Note 019 through spl_autoload_register to achieve automatic loading. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


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