php自動負載檔案

來源:互聯網
上載者:User

為瞭解決頁面多檔案引入的麻煩及難以管理 ,PHP提供了幾種自動負載檔案方案,這裡會一一介紹
自動載入最好做到類名和檔案名稱一至,高手路過。。

首先貼下目錄結構
方法一:使用__autoload()魔術函數

app/home.php

<?phpclass home {    public static function say() {        echo 'hello';    }}

autoload.php

// set_include_path 設定包含路徑函數// PATH_SEPARATOR 分隔字元';'// get_include_path() 擷取設定路徑set_include_path('app/'.PATH_SEPARATOR.get_include_path());function __autoload($className) {    include_once($className.'.php');}home::say();
方法二:使用spl_autoload_register() spl:standard php library 標準PHP庫

app/home.php

<?phpclass home {    public static function say() {        echo 'hello';    }}

autoload.php

set_include_path('app/'.PATH_SEPARATOR.get_include_path());class autoload {    public static function load($className) {        include_once($className.'.php');    }}spl_autoload_register(['autoload', 'load']);// 也可以寫成 spl_autoload_register('autoload::load'); 靜態方式home::say();
方法三:spl_autoload_register() 配合namespace (要求檔案名稱和class名一至)

autoload.php

class autoload {    public static function load($fileName) {        $filePath = sprintf('%s.php', str_replace('\\', '/', $fileName));        require_once $filePath;    }}spl_autoload_register(['autoload', 'load']);

lib/page.php

namespace lib;class page {    public static function show() {        echo 'page';    }}

app/home.php

include_once "../autoload.php";$p = new \lib\page();$p::show();

當然也可以寫成

include_once "../autoload.php";use lib\page;page::show();// $p = new page();// $p->show();

謝謝關注~

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.