搜尋
首頁後端開發php教程php类的注册与自动加载__autoload_PHP教程

php类的注册与自动加载__autoload_PHP教程

Jul 13, 2016 pm 04:56 PM
autoloadphp函數載入執行註冊環境類別自動

__autoload() 是PHP执行环境中约定的一个函数而非某个类的方法,如果一个类在使用之前没有加载到当前文件,会自动调用 __autoload() 函数来加载该类,通常这些类的加载规则都是约定的,比如这些类包含在以类名命名的文件内,该方法可以实现类的按需加载,避免脚本执行前加载不必要的类从而降低资源占用、提交性能。

注意:__autoload() 内的错误不能被 try-catch 捕获。

 代码如下 复制代码

function __autoload($class_name){

     require_once(PATH.'/calsses/'.$class_name.'.php');

}

$obj1 = new mycalss1();

注册 __autoload() 自动调用的函数:

spl 代码库在 PHP5.0 之后默认自动启用

spl_autoload_register([callback]); //不将具体实现的加载代码写在 __autoload() 内,可使用该函数注册回调函数。

如果使用类的方法作为回调函数需要传入一个数组:

 代码如下 复制代码

spl_autoload_register(array('class_name'|$obj,'method_name'));

例如:

spl_autoload_register(array($this,'autoloadClass'));

spl_autoload_register(array('YiiBase','autoload'));// YII 框架的自动加载类的实现, YiiBase 类实现了一个autoload 方法。  spl_autoload_register() 可以注册多个加载函数,成功加载类文件之前将逐个尝试所有注册的加载函数。这在不同的类使用不同逻辑来导入类文件的时候很有用。

spl_autoload_unregister(); //取消某个注册的加载函数,参数与 spl_autoload_register() 相同.

spl_autoload_functions();// 以数组形式返回所有注册的 __autoload() 函数

 

spl_autoload(class_name[,file_extentions]); // __autoload() 函数的默认实现。 spl_autoload_register() 被调用时如果没有传入 函数名,则默认使用该函数,该函数的执行规则是: 类名转为小写作为文件名,传入的 file_extentions(多个扩展名以逗号隔开,默认为 .inc 和 .php)为扩展名,根据得到的文件名尝试在 php.ini 内设置的 include paths 中搜索。

 spl_autoload_call(class_name);//手动调用所有注册的 __autoload() 函数来主动加载类文件

spl_autoload_extentions([file_extentions]); //注册或返回 spl_autoload() 中可以使用的文件扩展名,扩展名可以是 .a.b 这样的形式,例如:

 

 代码如下 复制代码

spl_autoload_extentions(".class.php");

spl_autoload_register(); //使用spl_autoload() 来尝试自动加载类文件

//这样 spl_autoload('myclassName'); 会尝试加载 文件 "myclassName.class.php" .

实例

1、将需要注册的类放在一个数组中

 代码如下 复制代码


final class Utils {

    private function __construct() {

    }

    public static function getClasses($pre_path = '/') {
        $classes = array(
                'DBConfig' => $pre_path.'DBConfig/DBConfig.php',
                'User' => $pre_path.'Model/User.php',
                'Dao' => $pre_path.'Dao/Dao.php',
                'UserDao' => $pre_path.'Dao/UserDao.php',
                'UserMapper' => $pre_path.'Mapping/UserMapper.php',
        );
        return $classes;
    }
}
?>

2、注册数组

注意:步骤1中的类的路径都是相对于init.php而言的,不是相对于Utils而言的,这是因为我们通过init.php里的自动加载函数spl_autoload_register来require类的

 代码如下 复制代码


require_once '/Utils/Utils.php';
final class Init {
   
    /**
     * System config.
     */
    public function init() {
        // error reporting - all errors for development (ensure you have
        // display_errors = On in your php.ini file)
        error_reporting ( E_ALL | E_STRICT );
        mb_internal_encoding ( 'UTF-8' );
        //registe classes
        spl_autoload_register ( array ($this,'loadClass' ) );
    }
   
    /**
     * Class loader.
     */
    public function loadClass($name) {
        $classes = Utils::getClasses ();
        if (! array_key_exists ( $name, $classes )) {
            die ( 'Class "' . $name . '" not found.' );
        }
        require_once $classes [$name];
    }
}
$init = new Init ();
$init->init ();
?>

3、本例中在使用处test.php里require init.php

 

 代码如下 复制代码

require_once 'Init.php';

$dao = new UserDao();
$result = $dao->findByName('zcl');
?>

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/631580.htmlTechArticle__autoload() 是PHP执行环境中约定的一个函数而非某个类的方法,如果一个类在使用之前没有加载到当前文件,会自动调用 __autoload() 函数来加...
陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
高流量網站的PHP性能調整高流量網站的PHP性能調整May 14, 2025 am 12:13 AM

TheSecretTokeEpingAphp-PowerEdwebSiterUnningSmoothlyShyunderHeavyLoadInVolvOLVOLVOLDEVERSALKEYSTRATICES:1)emplactopCodeCachingWithOpcachingWithOpCacheToreCescriptexecution Time,2)使用atabasequercachingCachingCachingWithRedataBasEndataBaseLeSendataBaseLoad,3)

PHP中的依賴注入:初學者的代碼示例PHP中的依賴注入:初學者的代碼示例May 14, 2025 am 12:08 AM

你應該關心DependencyInjection(DI),因為它能讓你的代碼更清晰、更易維護。 1)DI通過解耦類,使其更模塊化,2)提高了測試的便捷性和代碼的靈活性,3)使用DI容器可以管理複雜的依賴關係,但要注意性能影響和循環依賴問題,4)最佳實踐是依賴於抽象接口,實現鬆散耦合。

PHP性能:是否可以優化應用程序?PHP性能:是否可以優化應用程序?May 14, 2025 am 12:04 AM

是的,優化papplicationispossibleandessential.1)empartcachingingcachingusedapcutorediucedsatabaseload.2)優化的atabaseswithexing,高效Quereteries,and ConconnectionPooling.3)EnhanceCodeWithBuilt-unctions,避免使用,避免使用ingglobalalairaiables,並避免使用

PHP性能優化:最終指南PHP性能優化:最終指南May 14, 2025 am 12:02 AM

theKeyStrategiestosigantificallyBoostPhpaPplicationPerformenCeare:1)UseOpCodeCachingLikeLikeLikeLikeLikeCacheToreDuceExecutiontime,2)優化AtabaseInteractionswithPreparedStateTementStatementStatementAndProperIndexing,3)配置

PHP依賴注入容器:快速啟動PHP依賴注入容器:快速啟動May 13, 2025 am 12:11 AM

aphpdepentioncontiveContainerIsatoolThatManagesClassDeptions,增強codemodocultion,可驗證性和Maintainability.itactsasaceCentralHubForeatingingIndections,因此reducingTightCightTightCoupOulplingIndeSingantInting。

PHP中的依賴注入與服務定位器PHP中的依賴注入與服務定位器May 13, 2025 am 12:10 AM

選擇DependencyInjection(DI)用於大型應用,ServiceLocator適合小型項目或原型。 1)DI通過構造函數注入依賴,提高代碼的測試性和模塊化。 2)ServiceLocator通過中心註冊獲取服務,方便但可能導致代碼耦合度增加。

PHP性能優化策略。PHP性能優化策略。May 13, 2025 am 12:06 AM

phpapplicationscanbeoptimizedForsPeedAndeffificeby:1)啟用cacheInphp.ini,2)使用preparedStatatementSwithPdoforDatabasequesies,3)3)替換loopswitharray_filtaray_filteraray_maparray_mapfordataprocrocessing,4)conformentnginxasaseproxy,5)

PHP電子郵件驗證:確保正確發送電子郵件PHP電子郵件驗證:確保正確發送電子郵件May 13, 2025 am 12:06 AM

phpemailvalidation invoLvesthreesteps:1)格式化進行regulareXpressecthemailFormat; 2)dnsvalidationtoshethedomainhasavalidmxrecord; 3)

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)