Note 019 automatic loading through spl_autoload_register

Source: Internet
Author: User
Note 019 automatic loading through spl_autoload_register

Spl_autoload_register

(PHP 5> = 5.1.2, PHP 7)

Spl_autoload_register-registers a given function as the _ autoload implementation

Syntax

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

Description

Through this function, you can specify the addressing mode for the loaded class, so that you do not need to request and include in large batches. The system automatically searches for classes to be instantiated under the corresponding location according to the specified rules. Although this method is relatively low-level, we generally do not need to do this work when there is a framework. But it is inevitable that I still need to use it. for example, when I write this blog, I need to execute scripts on my own. at this time, I cannot go around. The following example shows a simple automatically loaded program 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: Anonymous functions can be used only in PHP 5.3 and later versions. if you find that they are unavailable, check your PHP version. Here, I simply specify all the classes to be searched under my src folder. the class name is exactly the same as the file name.

The above is the content automatically loaded by note 019 through spl_autoload_register. For more information, see PHP Chinese website (www.php1.cn )!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.