溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何使用PHP中的spl_autoload_register() 和 __autoload() 函數(shù)

發(fā)布時(shí)間:2021-10-27 09:47:44 來源:億速云 閱讀:155 作者:iii 欄目:編程語言

本篇內(nèi)容介紹了“如何使用PHP中的spl_autoload_register() 和 __autoload() 函數(shù)”的有關(guān)知識(shí),在實(shí)際案例的操作過程中,不少人都會(huì)遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

如何使用PHP中的spl_autoload_register() 和 __autoload() 函數(shù)

在日常開發(fā)使用時(shí),我們面向?qū)ο蟪绦蛟O(shè)計(jì)的基本思想是,通常情況下習(xí)慣為每個(gè)類都創(chuàng)建一個(gè)單獨(dú)的PHP源文件,這樣的話為后來的維護(hù)提供便利,同時(shí)也很容易對類進(jìn)行復(fù)用。

在PHP中可以通過spl_autoload_register() __autoload() 函數(shù)來實(shí)現(xiàn)類的自動(dòng)加載功能,這樣可以節(jié)省我們的編程時(shí)間和精力。那接下來我們就分別來介紹一下這兩個(gè)函數(shù)吧。

__autoload()函數(shù)

__autoload()函數(shù)準(zhǔn)確來說它是魔術(shù)方法,我們在《五分鐘帶你了解PHP中的魔術(shù)方法(實(shí)例詳解)》中詳細(xì)的介紹了一些常用的魔術(shù)方法,其中講到,它是自動(dòng)調(diào)用的,也就是需要早特定條件下才會(huì)調(diào)用函數(shù)。

當(dāng)我們 new 一個(gè)類時(shí),如果當(dāng)前源文件中找不到這個(gè)類,PHP 則會(huì)自動(dòng)調(diào)用 __autoload() 函數(shù),并將類名傳遞給 __autoload() 函數(shù)。這就是__autoload()函數(shù)調(diào)用的特定條件。它的語法格式如下:

function __autoload($class){
    // 方法體
}

其中我們需要注意的是:

  • $class 為要加載的類名。

  • __autoload() 函數(shù)在當(dāng)前源文件中只能定義一次。

  • 想要使用 __autoload() 函數(shù)自動(dòng)加載類文件,類文件的名稱需要與類名相同,另外一個(gè)類文件中只能定義一個(gè)類。

接下來我們通過示例來看一下__autoload() 函數(shù)的使用,示例如下:

<?php
    function __autoload($class){
        $file = './'.$class.'.php';
        include_once($file);
    }
    $obj = new Demo();
?>

運(yùn)行上面的代碼,會(huì)自動(dòng)加載同目錄下的 Demo.php 文件,Demo.php 中的代碼如下所示:

<?php
    class Demo{
    }
?>

其中我們需要注意的是:__autoload() 函數(shù)自 PHP7.2.0 起已被棄用,可以使用 spl_autoload_register() 函數(shù)代替。

spl_autoload_register() 函數(shù)

spl_autoload_register()函數(shù)可以指定一個(gè)函數(shù)來替代__autoload()函數(shù)的功能,

spl_autoload_register([$autoload_function [, $throw = true [, $prepend = false ]]])

其中需要注意的是:

  • $autoload_function:要替代 __autoload() 函數(shù)的函數(shù)名稱,也可以是一個(gè)匿名函數(shù)。如果沒有提供任何參數(shù),則自動(dòng)注冊 autoload 的默認(rèn)實(shí)現(xiàn)函數(shù) spl_autoload();

  • $throw:用來設(shè)置 $autoload_function 無法成功注冊時(shí),spl_autoload_register() 函數(shù)是否拋出異常;

  • $prepend:如果是 true,則 spl_autoload_register() 函數(shù)會(huì)添加 $autoload_function 函數(shù)到隊(duì)列之首,否則添加到隊(duì)列尾部。

接下來我們通過示例來看一下,示例如下:

<?php
    spl_autoload_register('loadClass');
    function loadClass($class){
        $file = './'.$class.'.php';
        include_once($file);
    }
    $obj = new Demo();
?>

上述示例中使用 spl_autoload_register() 函數(shù)指定另一個(gè)函數(shù)來替代 __autoload() 函數(shù)。

“如何使用PHP中的spl_autoload_register() 和 __autoload() 函數(shù)”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

php
AI