PHP 類自動載入


簡介

要使用在其他 PHP 指令碼中定義的類,我們可以將其與 include 或 require 語句結合使用。但是,PHP 的自動載入功能不需要如此明確的包含。相反,當使用類(用於宣告其物件等)時,如果已使用 spl_autoload_register() 函式將其註冊,PHP 解析器將自動載入它。因此,可以註冊任意數量的類。透過這種方式,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
";       include $file;    } else {       throw new Exception("Unable to load $className.");    } }); try {    $obj1 = new test1();    $obj2 = new test10(); } catch (Exception $e) {    echo $e->getMessage(), "
"; } ?>

輸出

這將產生以下結果。−

Unable to load test1.

更新於:2020-09-18

2K+ 閱讀

開啟你的 事業

完成此課程可獲得認證

開始學習
廣告
© . All rights reserved.