它不是難學的PHP-FIG SP4 autoload標準和自己做。這使用spl_autoload_register()
,您可以使用多個自動加載器。下面是一個我剛剛閱讀PHP-FIG標準和PHP手冊的自助式自動加載器類的示例。
<?php
namespace Acme\Framework; //Just to use namespaces in this example.
class Autoloader
{
private function __construct()
{
;
}
private function __clone()
{
;
}
private static function autoload($qualifiedClassName)
{
$nsPrefix = 'Acme\\';
$baseDir = 'C:/public/www/acme/src/'; // /public/www/acme/src/
$nsPrefixLength = strlen($nsPrefix);
if (strncmp($nsPrefix, $qualifiedClassName, $nsPrefixLength) !== 0) {
return; //Go to next registered autoloader function/method.
}
$file = $baseDir . str_replace('\\', '/', substr($qualifiedClassName, $nsPrefixLength)) . '.php'; //substr() returns the string after $nsPrefix.
if (!file_exists($file)){
echo "<h1>$file</h1>";
throw new \RuntimeException("The file {$file} does not exist!");
}
if (!is_file($file)){
throw new \RuntimeException("The file {$file} is not a regular file!");
}
if (!is_readable($file)){
throw new \RuntimeException("The file {$file} is not readable!");
}
require $file;
}
public static function init()
{
/*
Just make another method in this class and alter this code
to run spl_autoload_register() twice.
*/
if(!spl_autoload_register(['self', 'autoload']))
{
throw new \RuntimeException('Autoloader failed to initialize spl_autoload_register().');
}
}
}
我在引導時使用它。
require 'Autoloader.php'; //Autoloader for objects.
Autoloader::init();
這可以被改變,以支持其他自動加載代碼在不同的目錄。
我希望這是有幫助的。祝你好運,並希望你的項目取得成功!
真誠,
安東尼·拉特利奇
使用作曲家之一,是迄今爲止最容易的。 – Augwa
使用最適合你的東西。 –