【问题标题】:Namespace, use reach file one folder up命名空间,使用到达文件上一个文件夹
【发布时间】:2013-03-06 18:54:38
【问题描述】:

我试图访问一个类文件,我在顶部定义了命名空间,其中包含以下内容: 文件:config.php

namespace Config;

class Config
{
    // Stuffs
}

文件结构是这样的

public_html
- admin
-- header.php
-- footer.php
-- file-trying-to-reach-config.php
- config.php

我正在尝试从 file-trying-to-reach-config.php 访问 config.php 文件。在 file-trying-to-reach-config.php 的顶部,我正在使用:

use \Config;

但我不知道我是如何使用向上移动文件夹到达 config.php 的。谷歌搜索和堆叠,但没有找到任何关于它的信息。我是否误解了命名空间和使用的概念?

如何使用 file-trying-to-reach-config.php 访问 config.php?

【问题讨论】:

  • 命名空间不是用于创建目录结构(尽管经常以这种方式被滥用,或者反过来)。您应该定义一个自动加载函数,这样您就可以使用\Config\Config(这看起来很奇怪)而无需考虑它。

标签: php namespaces


【解决方案1】:

Use 运算符用于在 PHP 中为命名空间命名,如 this documentation 中所述。当您拥有复杂的命名空间时,这实质上使您能够为类创建短名称。

您需要将 config.php 文件 includerequire 放到您要调用它的位置。例如

<?php

   include_once('../config.php');
   $config = new \Config\Config();

如需更高级的处理方法,您可以查看Autoloading,它将自动执行包含位。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-18
    • 1970-01-01
    • 2011-05-05
    • 2015-05-10
    • 2019-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多