【发布时间】:2011-12-31 18:16:52
【问题描述】:
最近我开始在 PHP 中使用命名空间,我不喜欢选择的命名空间分隔符/(因为大多数人都有共同的感觉)/
下面我有一个在 PHP 中使用命名空间的非常基本/简单的示例。
我有一个Registry.class.php 文件,该文件在命名空间Library 中有一个Registry 类
我还有一个文件 Controller.class.php 下面有一个 Controller 类,它位于名为 Project 的命名空间中
现在在这个 Project 命名空间中,我需要访问位于不同命名空间 Library 中的 Registry object,因此我使用 use Library\Registry 来导入该命名空间
完成后,我可以像这样简单地访问我的Registry 类...
$this->registry = new Registry;
现在,如果我没有使用 use Library\Registry,那么我将不得不像这样访问它
$this->registry = new /Library/Registry;
这就是我的问题开始的地方。
对于这个简单的例子,我只是引入了Registry class,在一个真实的项目中,想象几个其他的类和命名空间被引入,所以我将使用use Library\Registry和use Library\SOME OTHER CLASS和use Library\YET ANOTHER CLASS等。 ..
然后我可以对对象/类进行操作,就好像它们在这个命名空间中一样) 而不是new /Library/Registry;
我想知道这是否被认为是不好的做法?它大大简化了事情并使代码看起来更干净IMO,但是如果这种方法有什么不好的地方,我想在使用这种方法编写大量代码之前知道。当我使用它们的命名空间 INSTEAD 实例化它们并使用 use /Path/to/Namespace/Classname 导入它们时,我应该是 pre-fixing 我的类吗?
请与我分享您的知识,我知道无论哪种方式都可以,但我想确定一下。下面添加了示例类和命名空间:
Controller.class.php
<?php
namespace Project
{
use Library\Registry;
class Controller
{
public $registry;
function __construct()
{
include('E:\Library\Registry.class.php');
$this->registry = new Registry;
}
function show()
{
$this->registry;
echo '<br>Registry was ran inside testcontroller.php<br>';
}
}
}
?>
Registry.class.php
<?php
// Registry.class.php
namespace Library
{
class Registry
{
function __construct()
{
echo 'Registry.class.php Constructor was ran';
}
}
}
?>
【问题讨论】:
标签: php namespaces