แนะนำตัว
เพื่อที่จะใช้คลาสที่กำหนดไว้ในสคริปต์ PHP อื่น เราสามารถรวมคลาสเข้ากับคำสั่ง include หรือ require อย่างไรก็ตาม คุณลักษณะการโหลดอัตโนมัติของ PHP ไม่ต้องการการรวมอย่างชัดเจน เมื่อใช้คลาส (สำหรับการประกาศอ็อบเจกต์ ฯลฯ ) PHP parser จะโหลดคลาสโดยอัตโนมัติ หากลงทะเบียนกับ spl_autoload_register() การทำงาน. สามารถลงทะเบียนเรียนกี่ชั้นก็ได้ วิธีนี้ทำให้ PHP parser ได้รับโอกาสสุดท้ายในการโหลดคลาส/อินเทอร์เฟซก่อนที่จะเกิดข้อผิดพลาด
ไวยากรณ์
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.