我有以下自动加载器:
spl_autoload_register(function($class) {
$class = ltrim($class, '\\');
$filename = '';
$namespace = '';
if ($last_ns_pos = strripos($class, '\\')) {
$namespace = strtolower(substr($class, 0, $last_ns_pos));
$class = substr($class, $last_ns_pos + 1);
$filename = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
}
$filename .= str_replace('_', DIRECTORY_SEPARATOR, $class) . '.php';
require $filename;
});
如果我想加载MyApp\Library\ClassOne
,这工作正常,因为该类位于 /MyApp/Library/ClassOne.php
。这满足one function of namespaces ;但是,我希望能够自动加载常量和函数的文件(例如 MyApp\Constants
和 MyApp\Functions
分别位于 MyApp\Constants.php
和 MyApp\Functions.php
)。
最佳答案
PHP 目前(从 PHP 5.5 开始)不支持自动加载除类之外的任何内容。
目前正在讨论自动加载函数和常量的功能,该功能可能会添加到下一版本(即 PHP 5.6)中,但尚未最终确定。
参见https://wiki.php.net/rfc/autofunc了解更多详情。
关于php - 如何创建/使用基于 namespace 的 PHP 自动加载器来加载类以及常量和函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20707118/