自動載入類的另一種方式實現問題

來源:互聯網
上載者:User
hello,看了手冊上關於自動載入的另一種更快速的方式後,動手試了下,發現挺好用的。不過碰到了個小問題,就是當new class()的那個檔案和包含類的檔案夾不是屬於同級的時候不知道如何自動載入了。
index.php:

namespace inc;spl_autoload_extensions('.class.php');spl_autoload_register();new a();

inc\a.class.php:

namespace inc;class a{    function __construct(){        echo 'a';    }}

上面這樣是可以輸出a的,但是當把index.php放到比如index\index.php的時候就沒法載入類了。請教下這種情況下有沒有好的解決辦法。
補充下,自己寫載入程式可以,但是比較喜歡那老外的方法,2個函數就讓php自動完成載入,不需要寫額外的代碼,好神奇。

回複內容:

hello,看了手冊上關於自動載入的另一種更快速的方式後,動手試了下,發現挺好用的。不過碰到了個小問題,就是當new class()的那個檔案和包含類的檔案夾不是屬於同級的時候不知道如何自動載入了。
index.php:

namespace inc;spl_autoload_extensions('.class.php');spl_autoload_register();new a();

inc\a.class.php:

namespace inc;class a{    function __construct(){        echo 'a';    }}

上面這樣是可以輸出a的,但是當把index.php放到比如index\index.php的時候就沒法載入類了。請教下這種情況下有沒有好的解決辦法。
補充下,自己寫載入程式可以,但是比較喜歡那老外的方法,2個函數就讓php自動完成載入,不需要寫額外的代碼,好神奇。

推薦使用Composer進行自動載入, PSR-0規範.

這個載入方式在Zend中早已被內化,例如一個在Vendor/MyClass.php中的類,可以用Vendor_MyClass來調用。
怎麼區分檔案夾,這是需要自己寫程式實現的。如下代碼:

function _vendor_autoload($class) {  $parts = explode('\\', $class);  # Support for non-namespaced classes.  $parts[] = str_replace('_', DIRECTORY_SEPARATOR, array_pop($parts));  $path = implode(DIRECTORY_SEPARATOR, $parts);  $file = stream_resolve_include_path($path.'.php');  if($file !== false) {    require $file;  }}spl_autoload_register('_vendor_autoload');
  • 聯繫我們

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