官方是這么說的 自動加載類
很多開發者寫面向對象的應用程序時對每個類的定義建立一個 PHP 源文件。一個很大的煩惱是不得不在每個腳本開頭寫一個長長的包含文件列表(每個類一個文件)。 在 PHP 5 中,不再需要這樣了??梢远x一個 __autoload() 函數, 它會在試圖使用尚未被定義的類時自動調用。通過調用此函數,腳本引擎在 PHP 出錯失敗前有了最后一個機會加載所需的類。
最新的發展情況是
tip:
spl_autoload_register() 提供了一種更加靈活的方式來實現類的自動加載。因此,不再建議使用 __autoload()函數,在以后的版本中它可能被棄用。
一點想法
<pre>
相較于.Net的Namespace, PHP的namespace除了用來方便引用class,組織代碼結構,也用來提供需要文件的路徑查找。
腳本語言與編譯型語言的差異可見一斑。
</pre>
下面是LeanCloud的autoload
主要思路是通過$classname 拆分出是否是leancloud的class,并通過分解namespace classname得到php文件的路徑,并require到項目中來。
/**
* Enable autoload
*
* Require this file to enable autoload SDK classes on the fly. If you're
* using composer, it should be required automatically.
*
* @see https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader-examples.md
*
* @param string $class 完整的class名字.
* @return void
*/
spl_autoload_register(function ($class) {
// project-specific namespace prefix
$prefix = 'LeanCloud\\';
// base directory for the namespace prefix
$base_dir = __DIR__ . '/LeanCloud/';
// does the class use the namespace prefix?
/*
strlen 獲取leanCloud字符的長度,
strncmp **判斷兩個字符串前n個字符是否相等,區分大小寫**
比較截取長度為$len的兩個字符串是否一致
*/
$len = strlen($prefix);
if (strncmp($prefix, $class, $len) !== 0) {
// no, move to the next registered autoloader
return;
}
// get the relative class name
$relative_class = substr($class, $len);
// replace the namespace prefix with the base directory, replace
// namespace separators with directory separators in the relative
// class name, append with .php
$file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
// if the file exists, require it
if (file_exists($file)) {
require $file;
}
});