>백엔드 개발 >PHP 튜토리얼 >PHP __autoload 및 spl_autoload

PHP __autoload 및 spl_autoload

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB원래의
2016-07-29 09:04:181410검색
__autoload의 가장 큰 결함은 여러 자동 로드 방법을 가질 수 없다는 것입니다.
다음 시나리오를 생각해 보세요. 귀하의 프로젝트에는 __autoload가 있고 다른 사람의 프로젝트에도 __autoload가 있습니다. 해결책은 __autoload를 수정하여 하나로 만드는 것인데, 이는 의심할 여지 없이 매우 번거로운 작업입니다.

따라서 spl의 자동 로드 시리즈 기능이 나타나도록 긴급하게 자동 로드 호출 스택을 사용해야 합니다. spl_autoload_register를 사용하여 여러 사용자 정의 자동 로드 기능을 등록할 수 있습니다.

PHP 버전이 5.1보다 큰 경우 spl_autoload를 사용할 수 있습니다. 먼저 spl의 여러 기능을 이해하세요.

PHP __autoload与spl_autoload

spl_autoload는 _autoload() 의 기본 구현입니다. include_path에서 $class_name(.php/.inc)을 찾습니다.

실제 프로젝트에서 일반적인 방법은 다음과 같습니다(클래스가 불가능할 때만 호출됩니다). 찾을 수 있음):

  // 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;
            }
        }
    });

위 내용은 PHP __autoload 및 spl_autoload 관련 내용을 소개하고 있으며, PHP 튜토리얼에 관심이 있는 친구들에게 도움이 되기를 바랍니다.

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.