我仍然遇到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