php - 无法在 PHP 的另一个命名空间内使用命名空间类

标签 php namespaces

我仍然无法使用 PHP5 命名空间。

我有一个名为 Project 的命名空间,我正在尝试访问此 Project 命名空间内名为 registry 的类,该命名空间的命名空间为Library 所以在文件的顶部是一个 Project 命名空间我使用这一行 use Library\Registry;

Registry 类在 Library 命名空间内

这应该有效,但它没有,相反,在这个 Project 命名空间中访问我的 registry 类的唯一方法是使用这个

$this->registry = new \Library\Registry;

我希望能够使用它...

$this->registry = new Registry;

这就是使用

的全部原因
use Library\Registry;

Project 命名空间文件的顶部


下面我在这样的文件夹结构中有 3 个小示例脚本。
Library/registry.class.php 我的库文件夹中的一个类
Controller/controller.class.php 和我的 Controller 目录中的类
Controller/testing.php 一个运行脚本的测试文件。

E:\Library\Registry.class.php文件

<?php
namespace Library
{
    class Registry
    {
        function __construct()
        {
            echo 'Registry.class.php Constructor was ran';
        }
    }
}
?>

E:\Controller\Controller.class.php文件

<?php
use Library\Registry;

namespace Project
{
    class Controller
    {
        public $registry;

        function __construct()
        {
            include('E:\Library\Registry.class.php');

            // This is where my trouble is
            // to make it work currently I have to use
            //  $this->registry = new /Library/Registry;
            // But I want to be able to use it like below and that is why
            // I have the `use Library\Registry;` at the top
            $this->registry = new Registry;
        }

        function show()
        {
            $this->registry;
            echo '<br>Registry was ran inside testcontroller.php<br>';
        }
    }
}
?>

E:\Controller\testing.php文件

<?php
use Project\Controller;

include('testcontroller.php');

$controller = new Controller();
$controller->show();

?>

我收到这个错误...

Fatal error: Class 'Project\Registry' not found in PATH to file

除非我在下面的 controller.class.php 文件中使用它

$this->registry = new \MyLibrary\Registry;

因为在顶部的那个文件中我有 use Library\Registry; 我应该能够像这样访问它...

$this->registry = new Registry;

请帮我把它拿到我可以那样使用它的地方

最佳答案

use Library\Registry;

namespace Project
{

相信这是错误的方法:您在全局命名空间中使用ing Library\Registry,然后打开Project 命名空间。

use 语句放在您要将其导入到的命名空间中。

namespace Project
{
    use Library\Registry;

关于php - 无法在 PHP 的另一个命名空间内使用命名空间类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8617265/

相关文章:

python - 函数创建的类的虚拟名称在函数返回后似乎仍然存在-python

ruby-on-rails - Rails 3 命名空间和自定义类的问题(未初始化常量)

php - 在 RouteServiceProvider 中找不到 Laravel 5 路由

c++ - 即使有守卫在场,编译器也会提示重新定义

php - 如何创建一个从代码中获取参数并返回字符串的函数?

php - Zend 框架中的模块自动加载器

kubernetes 客户端运行错误 : an empty namespace may not be set during creation

php - 如何在 REDIS 中以最有效的方式基于多个条件查询我的数据?

php - PDO 在 Mysql 中插入多个复选框值

javascript - 带文件上传的多步骤表单