소개
다른 PHP 스크립트에 정의된 클래스를 사용하기 위해 include 또는 require 문과 통합할 수 있습니다. 그러나 PHP의 자동 로딩 기능은 그러한 명시적 포함을 필요로 하지 않습니다. 대신, 클래스가 사용될 때(객체 선언 등) PHP 파서는 spl_autoload_register()로 등록된 경우 자동으로 로드합니다. 기능. 따라서 원하는 수의 클래스를 등록할 수 있습니다. 이렇게 하면 PHP 파서는 오류를 발생시키기 전에 클래스/인터페이스를 로드할 마지막 기회를 얻습니다.
구문
spl_autoload_register(function ($class_name) {
include $class_name . '.php';
}); 클래스는 처음 사용할 때 해당 .php 파일에서 로드됩니다.
자동 로딩 예시
이 예는 클래스가 자동 로드를 위해 등록되는 방법을 보여줍니다.
예시
<?php
spl_autoload_register(function ($class_name) {
include $class_name . '.php';
});
$obj = new test1();
$obj2 = new test2();
echo "objects of test1 and test2 class created successfully";
?> 출력
그러면 다음과 같은 결과가 생성됩니다. -
objects of test1 and test2 class created successfully
단, 클래스 정의가 있는 해당 .php 파일이 없으면 다음과 같은 에러가 출력됩니다.
Warning: include(): Failed opening 'test10.php' for inclusion (include_path='C:\xampp\php\PEAR') in line 4 PHP Fatal error: Uncaught Error: Class 'test10' not found
예외 처리로 자동 로드
예시
<?php
spl_autoload_register(function($className) {
$file = $className . '.php';
if (file_exists($file)) {
echo "$file included\n";
include $file;
} else {
throw new Exception("Unable to load $className.");
}
});
try {
$obj1 = new test1();
$obj2 = new test10();
} catch (Exception $e) {
echo $e->getMessage(), "\n";
}
?> 출력
그러면 다음과 같은 결과가 생성됩니다. -
Unable to load test1.