Home >Backend Development >PHP Tutorial >PHP __autoload与spl_autoload

PHP __autoload与spl_autoload

WBOY
WBOYOriginal
2016-07-29 09:04:181379browse
The biggest flaw of __autoload is that it cannot have multiple autoload methods.
Okay, think about the following scenario. Your project references a project of someone else. Your project has an __autoload, and someone else's project also has an __autoload. In this way, the two __autoloads conflict. The solution is to modify __autoload to become one, which is undoubtedly very cumbersome.

Therefore, we urgently need to use an autoload call stack, so that the autoload series functions of spl appear. You can use spl_autoload_register to register multiple custom autoload functions.

If your PHP version is greater than 5.1, you can use spl_autoload. First understand several functions of spl:

PHP __autoload与spl_autoload

spl_autoload is the default implementation of _autoload(), it will look for $class_name(.php/.inc) in include_path

actually In the project, the usual methods are as follows (only called when the class cannot be found):

  // Example to auto-load class files from multiple directories using the SPL_AUTOLOAD_REGISTER method.
    // It auto-loads any file it finds starting with class.<classname>.php (LOWERCASE), eg: class.from.php, class.db.php
    spl_autoload_register(function($class_name) {

        // Define an array of directories in the order of their priority to iterate through.
        $dirs = array(
            'project/', // Project specific classes (+Core Overrides)
            'classes/', // Core classes example
            'tests/',   // Unit test classes, if using PHP-Unit
        );

        // Looping through each directory to load all the class files. It will only require a file once.
        // If it finds the same class in a directory later on, IT WILL IGNORE IT! Because of that require once!
        foreach( $dirs as $dir ) {
            if (file_exists($dir.'class.'.strtolower($class_name).'.php')) {
                require_once($dir.'class.'.strtolower($class_name).'.php');
                return;
            }
        }
    });

The above introduces PHP __autoload and spl_autoload, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

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