spl_autoload_register 함수
spl_autoload_register 함수는 주어진 함수를 클래스 자동 로드 메서드 구현체로 등록합니다. PHP가 정의되지 않은 클래스를 만나면 등록된 모든 자동 로드 함수를 순차적으로 호출하며, 클래스 이름을 인자로 전달합니다. 첫 번째 매개변수는 자동 로드를 위한 callback 함수, 두 번째 매개변수(선택 사항)는 오류 발생 시 예외를 던질지 여부, 세 번째 매개변수(선택 사항)는 함수를 큐의 맨 앞에 추가할지 여부입니다.
문법
spl_autoload_register(callable $autoload_function [, bool $throw = true [, bool $prepend = false ]]);
예시
자동 로드 함수를 간단히 등록하기:
<?php
function my_autoloader($class) {
include 'classes/' . $class . '.php';
}
spl_autoload_register('my_autoloader');
// 이제 명시적인 include 없이 객체 생성 가능
$obj = new MyClass();
?>
예시
자동 로드를 위해 익명 함수 사용하기:
<?php
spl_autoload_register(function ($class) {
include 'lib/' . str_replace('\\', '/', $class) . '.php';
});
$obj = new Some\Namespace\MyClass();
?>
예시
여러 자동 로드 함수 등록하기:
<?php
spl_autoload_register('autoloader1');
spl_autoload_register('autoloader2');
spl_autoload_register('autoloader3', true, true); // 큐의 앞부분에 추가
// PHP는 autoloader3, autoloader1, autoloader2 순서로 함수를 호출합니다.
$obj = new MyClass();
?>
함께 보기
-
spl_autoload_functions 함수,
자동 로더를 반환합니다 -
spl_autoload_unregister 함수,
자동 로더를 제거합니다 -
class_exists 함수,
클래스를 확인합니다