Giới thiệu
Để sử dụng lớp được định nghĩa trong script PHP khác, ta có thể include/require nó. Tuy nhiên, tính năng autoloading của PHP không cần include tường minh. Thay vào đó, khi một lớp được sử dụng (khai báo đối tượng, v.v.), PHP parser sẽ tự động tải nó nếu đã được đăng ký với hàm spl_autoload_register(). Bất kỳ số lượng lớp nào cũng có thể đăng ký như vậy. Cách này cho PHP parser cơ hội cuối cùng để tải class/interface trước khi báo lỗi.
Cú pháp
spl_autoload_register(function ($class_name) {
include $class_name . '.php';
});
Lớp sẽ được tải từ file .php tương ứng khi nó được sử dụng lần đầu.
Ví dụ autoloading cơ bản
<?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";
?>
Kết quả
objects of test1 and test2 class created successfully
Tuy nhiên, nếu file .php chứa định nghĩa lớp không tìm thấy, lỗi sau sẽ hiển thị:
Warning: include(): Failed opening 'test10.php' for inclusion PHP Fatal error: Uncaught Error: Class 'test10' not found
Autoloading với xử lý ngoại lệ (Exception handling)
<?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";
}
?>
Kết quả
Unable to load test10.