溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

PHP文件自動加載的使用方法

發(fā)布時間:2021-06-30 16:32:59 來源:億速云 閱讀:137 作者:chen 欄目:開發(fā)技術(shù)

本篇內(nèi)容主要講解“PHP文件自動加載的使用方法”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“PHP文件自動加載的使用方法”吧!

傳統(tǒng)上,在PHP里,當我們要用到一個class文件的時候,我們都得在文檔頭部require或者include一下:

<?php
require_once('../includes/functions.php');
require_once('../includes/database.php');
require_once('../includes/user.php');
...

但是一旦要調(diào)用的文檔多了,就得每次都寫一行,瞅著也不美觀,有什么辦法能讓PHP文檔自動加載呢?

<?php
function __autoload($class_name)
{
  require "./{$class_name}.php";
}

對,可以使用PHP的魔法函數(shù)__autoload(),上面的示例就是自動加載當前目錄下的PHP文件。當然,實際當中,我們更可能會這么來使用:

<?php
function __autoload($class_name)
{
  $name = strtolower($class_name);
  $path = "../includes/{$name}.php";
  
  if(file_exists($path)){
     require_once($path);
    }else{
      die("the file {$class_name} could not be found");
    }
}

也即是做了一定的文件名大小寫處理,然后在require之前檢查文件是否存在,不存在的話顯示自定義的信息。

類似用法經(jīng)常在私人項目,或者說是單一項目的框架中見到,為什么呢?因為你只能定義一個__autoload function,在多人開發(fā)中,做不到不同的developer使用不同的自定義的autoloader,除非大家都提前說好了,都使用一個__autoload,涉及到改動了就進行版本同步,這很麻煩。

也主要是因為此,有個好消息,就是這個__autoload函數(shù)馬上要在7.2版本的PHP中棄用了。

Warning This feature has been DEPRECATED as of PHP 7.2.0. Relying on this feature is highly discouraged.
那么取而代之的是一個叫spl_autoload_register()的東東,它的好處是可以自定義多個autoloader.

//使用匿名函數(shù)來autoload
spl_autoload_register(function($class_name){
  require_once('...');
});
//使用一個全局函數(shù)
function Custom()
{
  require_once('...');
}

spl_autoload_register('Custom');
//使用一個class當中的static方法
class MyCustomAutoloader
{
  static public function myLoader($class_name)
  {
    require_once('...');    
  }
}

//傳array進來,第一個是class名,第二個是方法名
spl_autoload_register(['MyCustomAutoloader','myLoader']);
//甚至也可以用在實例化的object上
class MyCustomAutoloader
{
  public function myLoader($class_name)
  {
  }
}

$object = new MyCustomAutoloader;
spl_autoload_register([$object,'myLoader']);

值得一提的是,使用autoload,無論是__autoload(),還是spl_autoload_register(),相比于require或include,好處就是autoload機制是lazy loading,也即是并不是你一運行就給你調(diào)用所有的那些文件,而是只有你用到了哪個,比如說new了哪個文件以后,才會通過autoload機制去加載相應文件。

當然,laravel包括各個package里也是經(jīng)常用到spl_autoload_register,比如這里:

/**
 * Prepend the load method to the auto-loader stack.
 *
 * @return void
 */
protected function prependToLoaderStack()
{
  spl_autoload_register([$this, 'load'], true, true);
}

到此,相信大家對“PHP文件自動加載的使用方法”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進入相關(guān)頻道進行查詢,關(guān)注我們,繼續(xù)學習!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

php
AI