中央論壇 - CENTER BBS
標題:
[PHP] 函數spl_autoload_register() & __autoload()介紹及用法實作
[打印本頁]
作者:
郭子錢
時間:
2013-9-24 09:56
標題:
[PHP] 函數spl_autoload_register() & __autoload()介紹及用法實作
1.__autoload() —— 自動加載函數
我把很多個類文件以類名.class.php的形式存放在class目錄中,在class的同級目錄中建立一個index.php。進入class目錄裡面分別建立class1.class.php、class2.class.php、class3.class.php文件,分別為裡面的文件添加一下代碼
<?php
//class1.class.php中
class class1{
public function __construct(){
echo "class1";
}
}
?>
<?php
//class2.class.php中
class class2{
public function __construct(){
echo "class2";
}
}
?>
<?php
//class3.class.php中
class class3{
public function __construct(){
echo "class3";
}
}
?>
複製代碼
index.php文件中寫入
<?php
function __autoload($classname){
$filename = "./class/".$classname.".class.php";
if(is_file($filename)){
include $filename;
}
}
$test1 = new class1();
echo '<br/>';
$test1 = new class2();
echo '<br/>';
$test1 = new class3();
//结果是
class1
class2
class3
?>
複製代碼
我們成功的自動加載了class下面所有的要加載的類。
2.spl_autoload_register() —— 註冊__autoload()函數
class裡面的文件不做任何改變,只是簡單的改寫一下index.php
<?php
// 写一个loadclass函数
// loadclass函数不具备自动加载类的功能
function loadclass($classname){
$filename = "./class/".$classname.".class.php";
if(is_file($filename)){
include $filename;
}
}
// spl_autoload_register()函数让这个loadclass具备了自动加载类的功能
spl_autoload_register("loadclass");
$test1 = new class1();
echo '<br/>';
$test1 = new class2();
echo '<br/>';
$test1 = new class3();
?>
複製代碼
至於性能上面,發現很多框架裡面都是用的spl_autoload_register(),參考文獻說法是spl_autoload_register()較新且效能較好。
spl_autoload_register() 用法實驗過程:
第一步
,使用spl_autoload_register()函數注冊load()方法
代碼如下:
<?php
function load(){
require_once 'lib.php';
}
spl_autoload_register('load');
?>
複製代碼
其中lib.php文件代碼如下
代碼如下:
<?php
class className{
function method(){
echo 'a method in class';
}
}
function onlyMethod(){
echo 'method only';
}
?>
複製代碼
說明:lib.php文件为一個className類和一個onlyMethod函數
第二步
,調用自動加載類
代碼如下:
$class = new className();
$class->method();
onlyMethod();
複製代碼
輸出:
a method in class
method only
說明:實例化className類,並調用類method()函數,同時調用onlyMethod()方法,輸出正常,沒有出現錯誤
第三步
,直接調用函數
onlyMethod();
複製代碼
說明:沒有實例化類,直接調用lib.php文件中的onlyMethod()函數
輸出:
Fatal error: Call to undefined function onlyMethod() in '...(省略路徑)'
第四步
,實例化className類,再直接調用
$class = new className();
onlyMethod();
複製代碼
輸出:method only
從上面的四步實驗發現,如果加載的文件包含函數,使用則一定需要實例化�堶悸疑�,否則就產生異常情況 Call to undefined function錯誤,具體在使用中要注意一下。
歡迎光臨 中央論壇 - CENTER BBS (https://centerbbs.com/)
Powered by Discuz! X3