표준 PHP 라이브러리(SPL) spl_autoload_register
(PHP 5 >= 5.1.0, PHP 7, PHP 8)
spl_autoload_register — 주어진 함수를 __autoload() 구현으로 등록
설명
spl_autoload_register(?callable $callback
= null
, bool $throw
= true
, bool $prepend
= false
): bool
spl에서 제공하는 __autoload 대기열에 함수를 등록합니다. 대기열이 아직 활성화되지 않은 경우 활성화됩니다.
코드에 기존 __autoload() 함수가 있는 경우 이 함수는 __autoload 대기열에 명시적으로 등록되어야 합니다. 이는 spl_autoload_register()가 __autoload() 함수의 엔진 캐시를 spl_autoload() 또는 spl_autoload_call()로 효과적으로 대체하기 때문입니다.
멀티플 자동 로드 함수가 있어야 하는 경우 spl_autoload_register()가 이를 허용합니다. 자동 로드 함수의 대기열을 효과적으로 생성하고 정의된 순서대로 각 함수를 실행합니다. 대조적으로 __autoload()는 한 번만 정의할 수 있습니다.
매개변수
callback
- 자동 로드 함수를 등록 중입니다.
null
이면 spl_autoload()의 기본 구현이 등록됩니다.callback(string
$class_name
): void throw
- 이 매개변수는
callback
을 등록할 수 없을 때 spl_autoload_register()가 예외를 발생시켜야 하는지 여부를 지정합니다. prepend
- true인 경우 spl_autoload_register()는 자동 로더를 추가하는 대신 자동 로드 대기열에 자동 로더를 추가합니다.
반환 값
성공하면 true
를, 실패하면 false
를 반환합니다.
변경 로그
버전 | 설명 |
---|---|
8.0.0 | callback 은 이제 nullable입니다. |
Examples
예제 #1 spl_autoload_register() as a replacement for an __autoload() function
<?php
// function __autoload($class) {
// include 'classes/' . $class . '.class.php';
// }
function my_autoloader($class) {
include 'classes/' . $class . '.class.php';
}
spl_autoload_register('my_autoloader');
// Or, using an anonymous function
spl_autoload_register(function ($class) {
include 'classes/' . $class . '.class.php';
});
?>
예제 #2 클래스가 로드되지 않은 spl_autoload_register() 예제
<?php
namespace Foobar;
class Foo {
static public function test($name) {
print '[['. $name .']]';
}
}
spl_autoload_register(__NAMESPACE__ .'\Foo::test');
new InexistentClass;
?>
위의 예는 다음과 유사한 결과를 출력합니다.
[[Foobar\InexistentClass]] Fatal error: Class 'Foobar\InexistentClass' not found in ...
기타
- __autoload() - 정의되지 않은 클래스 로드 시도