我仍然无法使用 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/