標籤:php ret 情況 echo else 註冊 並且 reg turn
第一種情況:檔案A.php中內容如下
<?php
class A{
public function __construct(){
echo ‘fff‘;
}
}
?>
檔案C.php 中內容如下:
<?php
function __autoload($class)
{
$file = $class . ‘.php‘;
if (is_file($file)) {
require_once($file);
}
}
$a = new A(); //這邊會自動調用__autoload,引入A.php檔案
?>
第二種情況:有時我希望能自訂autoload,並且希望起一個更酷的名字loader,則C.php改為如下:
<?php
function loader($class)
{
$file = $class . ‘.php‘;
if (is_file($file)) {
require_once($file);
}
}
spl_autoload_register(‘loader‘); //註冊一個自動載入方法,覆蓋原有的__autoload
$a = new A();
?>
第三種情況:我希望高大上一點,用一個類來管理自動載入
<?php
class Loader
{
public static function loadClass($class)
{
$file = $class . ‘.php‘;
if (is_file($file)) {
require_once($file);
}
}
}
spl_autoload_register(array(‘Loader‘, ‘loadClass‘));
$a = new A();
?>
當前為最佳形式。
通常我們將spl_autoload_register(*)放在入口指令碼,即一開始就引用進來。比如下面discuz的做法。
if(function_exist(‘spl_autoload_register‘)){
spl_autoload_register(array(‘core‘,‘autoload‘)); //如果是php5以上,存在註冊函數,則註冊自己寫的core類中的autoload為自動載入函數
}else{
function __autoload($class){ //如果不是,則重寫php原生函數__autoload函數,讓其調用自己的core中函數。
return core::autoload($class);
}
}
深入理解PHP類的自動載入機制方法