深入理解PHP類的自動載入機制方法

來源:互聯網
上載者:User

標籤: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類的自動載入機制方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.