Php 使用autoloader加载没有实例化类的文件
这是我的项目结构:Php 使用autoloader加载没有实例化类的文件,php,autoloader,Php,Autoloader,这是我的项目结构: - project -- src --- class1.php --- class2.php --- class3.php --- class4.php --- class.php - autoload.php 这就是我的自动加载器(autoload.php)的外观: 自动加载器加载类。如果您的配置代码在类之外,则无法自动加载它。也就是说,不能自动加载包含全局函数的文件。有关构造源代码树的公认方法,请参阅。每个文件应该有一个类、一个接口或一个摘要。@AlexHowansky
- project
-- src
--- class1.php
--- class2.php
--- class3.php
--- class4.php
--- class.php
- autoload.php
这就是我的自动加载器(autoload.php
)的外观:
自动加载器加载类。如果您的配置代码在类之外,则无法自动加载它。也就是说,不能自动加载包含全局函数的文件。有关构造源代码树的公认方法,请参阅。每个文件应该有一个类、一个接口或一个摘要。@AlexHowansky我知道PSR-4是用它做自动加载的;所以我应该将常量和其他函数放在一个类中,或者我可以在它们自己的名称空间中全局定义它们?这是一个意见问题,并且会因项目需要而有所不同。就个人而言,我尽量避免定义任何全局名称空间。有时我会将全局函数放入实用程序
类或类似的类中,因此当您通过实用程序::func()
调用它们时,它们将自动加载。自动加载程序加载类。如果您的配置代码在类之外,则无法自动加载它。也就是说,不能自动加载包含全局函数的文件。有关构造源代码树的公认方法,请参阅。每个文件应该有一个类、一个接口或一个摘要。@AlexHowansky我知道PSR-4是用它做自动加载的;所以我应该将常量和其他函数放在一个类中,或者我可以在它们自己的名称空间中全局定义它们?这是一个意见问题,并且会因项目需要而有所不同。就个人而言,我尽量避免定义任何全局名称空间。有时我会将全局函数放入实用程序类或类似类中,因此当您通过实用程序::func()
调用它们时,它们将自动加载。
<?php
/**
* @param string $class The fully-qualified class name.
* @return void
*/
spl_autoload_register(function ($class) {
// project-specific namespace prefix
$prefix = 'ProjectName';
// base directory for the namespace prefix
$base_dir = __DIR__ . '/src/';
// does the class use the namespace prefix?
$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;
}
});