在之前的文章中給大家?guī)砹恕禤HP中怎樣去判斷對(duì)象是否屬于一個(gè)類?》,其中詳細(xì)介紹了在PHP中應(yīng)該增陽區(qū)判斷一個(gè)對(duì)象是否屬于一個(gè)類的相關(guān)知識(shí),本篇文章我們來看一下PHP中的自動(dòng)加載機(jī)制。希望對(duì)大家有幫助!
在日常開發(fā)使用時(shí),我們面向?qū)ο蟪绦蛟O(shè)計(jì)的基本思想是,通常情況下習(xí)慣為每個(gè)類都創(chuàng)建一個(gè)單獨(dú)的PHP源文件,這樣的話為后來的維護(hù)提供便利,同時(shí)也很容易對(duì)類進(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ù)方法,我們?cè)凇段宸昼妿懔私釶HP中的魔術(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)注冊(cè) autoload 的默認(rèn)實(shí)現(xiàn)函數(shù) spl_autoload(); -
$throw
:用來設(shè)置 $autoload_function 無法成功注冊(cè)時(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ù)。
大家如果感興趣的話,可以點(diǎn)擊《PHP視頻教程》進(jìn)行