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');