PHP自动加载类—__autoload()和spl_autoload_register()
test.php
<?php
function __autoload($class_name)
{require_once $class_name . '.php';
}
$obj = new j();?>
?
當前目錄下有j.php
<?php
class j
{function __construct() {echo "成功加載";}
}
?>
正常輸出:成功加載
?
修改test.php代碼
<?php
function __autoload($class_name)
{require_once $class_name . '.php';
}
$obj = new k();
?>
運行test.php報錯:
Warning: require_once(k.php) [function.require-once]: failed to open stream: No such file or directory in F:\website\test.php on line 11
Fatal error: require_once() [function.require]: Failed opening required 'k.php' (include_path='.;C:\php5\pear') in F:\website\test.php on line 11
恢復test.php代碼
但是將j.php移到另外目錄錄入k下,
運行test.php報錯:
Warning: require_once(j.php) [function.require-once]: failed to open stream: No such file or directory in F:\website\test.php on line 11
Fatal error: require_once() [function.require]: Failed opening required 'j.php' (include_path='.;C:\php5\pear') in F:\website\test.php on line 11
這個時候是因為找不到j.php
所以需要修改test.php代碼
<?phpfunction __autoload($class_name)
{require_once "k/".$class_name . '.php';
}
$obj = new j();
?>
-----------------------------------------------------------------------------
為什么使用自動加載?
?
包含一般文件較少的情況會用手動包含要使用的類文件
當要包含大量類文件的時候,這樣就會顯得麻煩,就可以使用自動包含類。
類文件:test.php
class Test
{
?? public function __construct()
?? {
?????? echo __CLASS__.__FUNCTION__;
?? }
}
?
?
1.手動包含:
require_once('test.php');
$test = new Test();
?
?
2.使用__autoload()自動包含:
// 這樣實例化一個類的時候,將會自動包含同名的類文件
// 需要重載__autoload方法,自定義包含類文件的路徑
function __autoload($classname)
{
??? $class_file = strtolower($classname).".php";
??? if (file_exists($class_file)){
??????? require_once($class_file);
??? }
}
$test = new Test();
?
3.使用spl_autoload_register() 自定義的方法來加載文件
語法:bool? spl_autoload_register ( [callback $autoload_function] )
function myLoader($classname)
{
??? $class_file = strtolower($classname).".php";
??? if (file_exists($class_file)){
??????? require_once($class_file);
??? }
}
// 注冊自定義方法
spl_autoload_register("myLoader");
$test = new Test();
?
也可以使用類的方法來實現自定義的加載函數
class autoLoader
{
??? public static function myLoader($classname)
??? {
??????? $class_file = strtolower($classname).".php";
??????? if (file_exists($class_file)){
??????????? require_once($class_file);
??????? }
??? }
}
// 通過數組的形式傳遞類和方法,元素一為類名稱、元素二為方法名稱
// 方法為靜態方法
spl_autoload_register(array("autoLoader","myLoader"));
$test = new Test();
?
總結
以上是生活随笔為你收集整理的PHP自动加载类—__autoload()和spl_autoload_register()的全部內容,希望文章能夠幫你解決所遇到的問題。