Note 019 Automatic loading through spl_autoload_register

黄舟
Release: 2023-03-04 09:24:01
Original
1091 people have browsed it

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;
        }
    }
});
Copy after login

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)!


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!