繁体   English   中英

PHP OOP类和自动加载器

[英]PHP OOP classes and autoloader

我有自动加载器的PHP代码是这样的:

spl_autoload_extensions(".php"); // comma-separated list
spl_autoload_register(
function ($pClassName) {
spl_autoload(strtolower(str_replace("\\", "/", $pClassName)));
});

因此,我的索引如下:

<?php 
namespace index;
use request\request;

类请求位于以下文件夹中:

vendor/request/request.php

该类的名称空间是:

namespace request;
class request {
// protected functions here 
}

我收到以下错误:

Uncaught Error: Class 'request\request' not found

还尝试使用index \\ request和index \\ request \\ request。 错误是一样的!

问题是什么 ? 字符集也试图设置ANSI和UTF-8,这个问题不是来自字符集编码。

这看起来像是因为您的非供应商代码(索引和自动加载器)位于文件系统上的vendor目录之外。 如果您的index.php始终是入口点,那么这是一个非常简单的解决方法:确保spl_autoload函数知道vendor目录:

spl_autoload(getcwd() .'/vendor/'.strtolower(str_replace("\\", "/", $pClassName)));

您也可以使用__DIR__代替getcwd()来执行此操作,从技术上讲,这样做会更快。 我没有这样做,因为我不确定该自动加载代码在文件系统上的哪个位置。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM