為瞭解決頁面多檔案引入的麻煩及難以管理 ,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();
謝謝關注~