php - 在层次结构目录结构中使用 PHP 命名空间错误

标签 php namespaces

我正在使用文件夹结构如下:

classes
    -common.php
    -core.php
modules
    -index/index.php

我试图在我的 index.php 文件中使用 common.php 并且我面临错误:

Fatal error: Class 'classes\Common' not found in D:\xampp\htdocs\devmyproject\modules\index\index.php on line 7



我的代码:

commom.php 类:
**Directory:/root/classes/common.php**
<?php
namespace classes;

class Common
{

    function __construct()
    {

    }
}

我的 index.php 尝试使用 classes/commom.php 的文件
**Directory:/root/modules/index/index.php**
<?php
namespace modules\beneficiary;
use \classes as hp; 
include_once 'config.php';
$common = new \classes\Common();
//To Get Page Labels
$labels = $common->getPageLabels('1');

我在 config.php 中包含了 common.php
$iterator = new DirectoryIterator($classes);
foreach ($iterator as $file) {
    if ($file->isFile())
        include_once 'classes/' . $file;
}

我的尝试:

当我使用文件夹结构时它工作正常,如下所示:
classes
    -common.php
    -core.php
modules
    -index.php

如果我在模块内使用另一个文件夹,它会出错吗?我不确定使用命名空间时文件夹的层次结构有人可以帮助我吗?

最佳答案

你必须要么include index.php 中的 common.php(更好:使用其亲属 include_oncerequire_once 之一)或使用 spl_autoload_register() 设置自动加载器(或者,不推荐,编写 __autoload() 函数)。

关于php - 在层次结构目录结构中使用 PHP 命名空间错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18459169/

相关文章:

c++ - 在没有对象的情况下更改 class::variable 的默认值

php - CakePHP Fetch Assoc 相当于打印数组中的值?

javascript - 如何将数据从 Controller 放入 View 中的特定 div 元素中

php - 缩小 HTML 输出,但保留某些标签

sql - 使用现有命名空间查询 Oracle 中的 XML 表

C++ - 显式和隐式命名空间实现差异

clojure.tools/命名空间刷新失败,错误代码为 "No namespace: foo"

php - 从 PHP 中的静态方法访问私有(private)

php - 是否可以跟踪 magentos admin 中的所有/大部分更改?

c++ - 在 C++ 中,static 断言当前位置的声明不会包含在任何 namespace 中?