我正在寻找最干净、最优雅的方法来在 PHP 8 中构建操作系统安全的路径字符串,并将它们包含在我的自动加载函数中,如果可能的话,不使用
str_replace()
或 substr()
。
我有这样的文件结构:
NameOfProject
├──(...)
├──src
| ├──Controller
| | └──(...)
| ├──Helper
| | └──(...)
| ├──Model
| | └──(...)
| ├──View
| | └──(...)
└──index.php
src
文件夹中的每个类都有相应的命名空间,例如NameOfProject\src\Controller
。
我想使用 spl_autoload_register()
函数自动加载每个类。
这是我的代码:
<?php
//index.php
spl_autoload_register(function($class)
{
include
dirname(__FILE__, 2)
.'/'
.str_replace('\\', '/', $class)
.'.php';
});
我想知道是否有一种更优雅的方法来避免
str_replace()
,但如果没有它,路径字符串的串联将不起作用,因为 $class
始终返回命名空间(带反斜杠)而不是实际路径.
我读过 PHP 已经在函数内将正斜杠
/
转换为 DIRECTORY_SEPARATOR
,但我想我记得过去只使用正斜杠存在问题。
如果
str_replace()
必须存在,也许使用 DIRECTORY_SEPARATOR
合适?像这样:
str_replace('\\', DIRECTORY_SEPARATOR, $class)
我还考虑过从
$class
中删除类名的选项,但这也需要一个“丑陋”的 substr()
:
$class = substr($class, strrpos($class, "\\") + 1);
如果你的代码结构非常整洁,你可以使用默认的自动加载实现,请参阅本页中的注释:
set_include_path('parent folder of NameOfProject');
spl_autoload_register();
此方法将尝试从
NameOfProject\src\Controller\MyController
加载类 NameOfProject/src/Controller/MyController.php
。