【问题标题】:Is it bad to include all the Namespaces and access Classes with just their class name in PHP?在 PHP 中只包含所有的命名空间和访问类的类名是不是很糟糕?
【发布时间】: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\Registryuse Library\SOME OTHER CLASSuse 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


    【解决方案1】:

    命名空间的主要目的之一是防止大型代码库中以及共享代码和导入库之间的名称冲突。如果您没有名称冲突问题,那么我不一定认为使用每个类有什么问题。但是,如果您发现自己为所有类都这样做,那么我会质疑您为什么首先使用名称空间。如果您的代码将被其他人用作 API 或库,这对我来说似乎才有意义。

    【讨论】:

    • 我明白你在说什么。在上面的示例中,Library 是我要命名所有Library 类的东西,类似于框架,然后上面的控制器将模拟在项目中访问我的库。我想它可以在不修改我的库代码的情况下使用任何一种方式都很好
    猜你喜欢
    • 2010-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-16
    • 2015-07-08
    • 2013-04-17
    • 2015-10-29
    • 2012-05-02
    相关资源
    最近更新 更多