簡體   English   中英

在PHP中定義一個自動加載器函數的最佳方法是什么,它可以顯示在找不到類時導致調用它的哪一行?

[英]What is the best way to define an autoloader function in PHP that can show which line caused it to be called when it can't find a class?

Atm我有一個簡單的自動加載器,該加載器僅將下划線轉換為正斜杠,並在末尾粘貼在.php上。 自然地,這需要您將“應用程序目錄”添加到包含路徑。

當您嘗試使用找不到的類時,會出現問題。 在這種情況下,PHP只會發出一些可觀的警告和錯誤,這些警告和錯誤僅指向我的自動加載器功能作為源。

最簡單的方法是找出哪個文件在哪個行中導致自動加載器嘗試加載缺少的類?

添加如下內容:

if (!file_exists($class.'.php')) {
  echo '<pre>';
  debug_print_backtrace();
  echo '</pre>';
}

或做得更詳細:

if (!file_exists($class.'.php')) {
  // PSEUDO CODE!
  echo '<pre>';
  $debug = debug_backtrace();
  echo 'Line: '.$debug['line'];
  echo '</pre>';
}

這是我最終做的,但做了一些修改:

function classNameToPath($className) {
  // Add your code which converts a class name to a relative path and returns it
  // For example Databases_Connection => Databases/Connection.php
}

function __autoload($className) {
  $classFile = classNameToPath($className);
  $allIncludePaths = preg_split("/:/", get_include_path());
  foreach($allIncludePaths as $includePath) {
    if (file_exists("${includePath}/${classFile}")) {
      require_once($classFile);
      return;
    }
  }
  throw new Exception("Class not found {$clasSName}");
}

這使您可以將“ main”函數包裝在try塊中,在其中您可以捕獲這些異常並從異常中獲取stackTrace並將其回顯到例如<pre>元素內。 太喜歡了,您必須使用PHP自己編寫所有這些代碼;)好吧,即使您沒有捕獲未找到的類,PHP仍然會捕獲它們並自動顯示stacktrace,只是不在<pre>因此它將是一個如果您在瀏覽器中看到的話,一行大亂七八糟。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM