PHP自動加載類
在PHP5之前我們還可以使用PHP的自動加載函數 http://php.net/manual/zh/function.autoload.php __autoload()
,在PHP7之後官方推薦的就是
http://php.net/manual/zh/function.autoload.php __autoload()
http://php.net/manual/zh/function.spl-autoload-register.php sql_autoload_register()
這裡就拿它們做比較
__autoload()
VS
spl_autoload_register()
-
__autoload()
- 官方給出的說明是嘗試加載未定義的類
- 它的參數就隻有一個 string [$class],字元串類型的要加載的類名
- 沒有傳回值
<?php
//這裡我們建立TestClass.php
//./TestClass.php
namespace Test;
class TestClass
{
public function myTestClas()
{
echo "這是測試函數";
}
}
//這裡我們建立index.php
./index.php
<?php
function __autoload($className)
{
$fileName = __DIR__ . '/' . $className .".php";
include_once($fileName);
}
$obj = new TestClass();
$obj->myTestClass();
-
spl_autoload_register()
1.官方給出的說法是 注冊給定的函數作為 __autoload 的實作,就是我們通過這個函數注冊一個函數,我們在這個函數裡具體的實作,讓檔案函數自動加載
2.參數一:autoload_function
欲注冊的自動裝載函數。如果沒有提供任何參數,則自動注冊 autoload 的預設實作函數spl_autoload()。
參數二:throw
此參數設定了 autoload_function 無法成功注冊時, spl_autoload_register()是否抛出異常
參數三:prepend
如果是 true,spl_autoload_register() 會添加函數到隊列之首,而不是隊列尾部。
3.傳回值,成功傳回true,失敗傳回false
./TestClass.php
<?php
class TestClass
{
protected $_index;
public function __construct($index)
{
echo $this->_index = $index;
echo "<hr />";
echo "這是 spl_autoload_register()";
}
}
?>
./index.php
<?php
function myAutoload($class)
{
include __DIR__ . '/' . $class . '.php';
}
spl_autoload_register('myAutoload');
$obj = new TestClass('Index');
【這裡有一個比較正式的實作—》
https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md
<?php
function myAutoload($className)
{
$className = ltrim($className,'\\');
$fileName = '';
$namespace = '';
if ($lastNsPos = strrpos($className,'\\')) {
$namespace = substr($className,0,$lastNsPos);
$className = substr($className,$lastNsPos + 1);
$fileName = str_replace('\\',DIRECTORY_SEPARATOR,$namespace) . DIRECTORY_SEPARATOR;
}
$fileName .= str_replace('_',DIRECTORY_SEPARATOR,$className).'.php';
require $fileName;
}
spl_autoload_register('myAutoload');