我仍然遇到PHP5命名空间的问题。不能在PHP的另一个命名空间中使用命名空间类
我有一个命名空间称为Project
,我试图访问此Project
命名空间有Library
一个命名空间,以便在该文件的顶部是一个Project
命名空间我使用这行内称为registry
类use Library\Registry;
Registry
类是Library
命名空间内
这应该工作,但它并没有,而不是唯一的方式来访问我的registry
类这里面Project
命名空间是使用此
$this->registry = new \Library\Registry;
我希望能够改为使用此...
$this->registry = new Registry;
这是使用
use Library\Registry;
在Project
空间文件的顶部的全部原因
下面我有3个小考试在这样的文件夹结构中运行脚本。
Library/registry.class.php
在我的库文件夹
Controller/controller.class.php
和类在我的控制器目录
Controller/testing.php
测试文件来运行该脚本的类。
E:\图书馆\ Registry.class.php文件
<?php
namespace Library
{
class Registry
{
function __construct()
{
echo 'Registry.class.php Constructor was ran';
}
}
}
?>
E:\控制器\ 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:\控制器\ 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',它会导致一个致命的错误。在我的例子中,它导致了这个'分析错误:语法错误,意外的T_CLASS,期待','或';'在第8行的E:\ Controller \ controller.class.php中# – JasonDavis 2011-12-23 14:51:59
@jasondavis不,那是因为我忘了在分隔符的末尾加上分号。试用我编辑的版本。 (顺便说一句,这应该是相当明显的错误...) – lonesomeday 2011-12-23 14:58:44
你说得对,我应该发现。它似乎在工作,这是否应该始终这样做?命名空间声明之后?每当我想我完全用这些命名空间获得它,弹出一些不起作用的命令空间,我就应该说我的麻烦开始了。谢谢你的帮助。在看C#项目时,他们是这样做的,所以我认为这会增加混淆 – JasonDavis 2011-12-23 15:10:55