Note 019 automatic loading via Spl_autoload_register

Source: Internet
Author: User

Spl_autoload_register

(PHP 5 >= 5.1.2, PHP 7)

spl_autoload_register-registering a given function as an implementation of the __autoload

Grammar

BOOL Spl_autoload_register ([Callable $autoload _function [, bool $throw = True [, bool $prepend = false]]])

Description

With this function, you can specify the addressing method for the loaded class so that you do not have to require and include in large batches. The system will automatically follow the specified rules to the corresponding location to find the class that needs to be instantiated. Although this method is relatively low-level, in the case of a framework, we generally do not need to do this work. But inevitably there is a time to use, such as when I write this blog, I need to churn script, this time, will not open. The following example is a simple auto-loading program that I want to use 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 the anonymous function is PHP 5.3 and above can be used, if found not to use, check your PHP version. I'm simply specifying all classes in my Src folder to look for, and the class name is exactly the same as the file name.

The above is the note 019 through Spl_autoload_register implementation of automatic loading content, more relevant content please pay attention to topic.alibabacloud.com (www.php.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.