php 28 類的自動載入

2021-08-28 22:18:21 字數 2112 閱讀 9812

法一:__autoload()魔術方法實現

//set_include_path()設定include預設查詢所有類的目錄

//get_include_path():獲取當前路徑;path_separator:路徑分割符;"lib/":拼接lib路徑

set_include_path

(get_include_path()

.path_separator

."lib/"

);

當前位置新建lib檔案,並其內部建立test.php和test1.php,內部再設定下面new到的類

//設定include預設查詢所有類的目錄

set_include_path

(get_include_path()

.path_separator

."lib/");

function

__autoload

($classname

)new

test()

;//我是lib檔案下的test.php中的text類

newtest1()

;//我是lib檔案下的test1.php中的text1類

法二:spl_autoload_register()
function

__autoload

($class_name

)//失效

function

classloader

($class_name

)//把函式註冊至spl的__autoload函式棧中,並移除系統預設的__autoload()

spl_autoload_register

('classloader');

//下面的顯示說明遮蔽了__autoload()

newtest()

;//spl load class:test

當前位置新建lib檔案,並其內部建立test.php和test1.php,內部再設定下面new到的類

//設定include預設查詢所有類的目錄

set_include_path

(get_include_path()

.path_separator

."lib/");

function

classloader

($classname

)function

addclassloader

($classname

)//註冊兩個

spl_autoload_register

('classloader');

spl_autoload_register

('addclassloader');

newtest()

;//classloader test 我是lib檔案下的test.php中的text類

newtest1()

;//classloader test1 我是lib檔案下的test1.php中的text1類

//乙個類先從第乙個註冊中找,若找不到,再從第二個註冊中找,以此類推

newt()

;//classloader t addclassloader t

//設定include預設查詢所有類的目錄

set_include_path

(get_include_path()

.path_separator

."lib/");

class

autoload

}spl_autoload_register

(array

('autoload'

,'loadclass'))

;new

test()

;//autoload 中的 loadclass test 我是lib檔案下的test.php中的text類

newtest1()

;//autoload 中的 loadclass test1 我是lib檔案下的test1.php中的text1類

php自動載入類,PHP中類的自動載入的方法

類的自動載入是指,在外面的頁面中,並不需要去 引入 類檔案,但是程式會在需要的時候動態載入需要的類檔案。方法1 使用 autoload魔術函式 當程式需要某個類時,就會去呼叫該函式,該函式我們需要自己去定義並在其中寫好載入類檔案的通用語句。需要類是自動呼叫,而且會傳進來乙個類名,這個案例的檔名為21...

php自動載入類

php類的自動載入機制 php的自動載入 在php5以前,我們要用某個類或類的方法,那必須include或者require,之後才能使用,每次用乙個類,都需要寫一條include,麻煩 php作者想簡單點,最好能引用乙個類時,如果當前沒有include進來,系統能自動去找到該類,自動引進 於是 au...

PHP 自動載入類

在專案開發中,因為乙個檔案中只能寫乙個類,並且在執行過程中會有很多的類參與,如果乙個乙個的載入很麻煩,所以,就需要乙個機制實現在php執行過程中自動載入需要的類。1.2.1 類的規則 乙個檔案中只能放乙個類 必須 檔名和類名同名 必須 類檔案以.class.php結尾 不是必須 1.2.2 手動載入...