【问题标题】:Declaring two namespaces in the one file在一个文件中声明两个命名空间
【发布时间】:2014-03-24 10:31:10
【问题描述】:

正如php reference中所说的

命名空间是使用命名空间关键字声明的。一个文件包含 命名空间必须在文件顶部声明命名空间之前 任何其他代码 - 除了一个例外:declare 关键字。

但我们在参考文献中还有以下代码 sn-p:

<?php
namespace MyProject;

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */  }

namespace AnotherProject; //This namespace declaration doesn't located at the top of the file. It's unclear.

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */  }
?>

【问题讨论】:

    标签: php namespaces declaration declare


    【解决方案1】:

    其中一个在顶部声明为MyProject 下的前三行引用MyProject 命名空间,而AnotherProject 下的其他三行引用AnotherProject 命名空间。 如果至少有一个命名空间被声明为顶部,则文件将被正确解析(命名空间将动态切换)

    为了更清楚,你甚至可以这样做

    <?php
    namespace MyProject {
    
    const CONNECT_OK = 1;
    class Connection { /* ... */ }
    function connect() { /* ... */  }
    }
    
    namespace AnotherProject {
    
    const CONNECT_OK = 1;
    class Connection { /* ... */ }
    function connect() { /* ... */  }
    }
    ?>
    

    但强烈建议不要在同一个 php 脚本中声明两个命名空间

    【讨论】:

    • 显然与A file containing a namespace must declare the namespace at the top of the file before any other code相矛盾。你能解释一下吗?
    • @DmitryFucintv:你为什么这么说?我可以在所有 php 代码之前完美地看到文件顶部的命名空间声明。正如我在回答中所说,至少应该在顶部声明一个命名空间,其他命名空间需要在之后声明(因此不在顶部),因为声明下的所有代码都将引用“新”命名空间。想想你可以在顶部声明三个命名空间的场景:下面的代码应该引用哪个命名空间?
    • 感谢您的评论。但是at least one namespace should be declarated at the top 没有在语言参考中指定。你为什么这么认为?
    • @DmitryFucintv 经验证据。正如 deceze 在他的回答中所说,在 php 文件中间声明一个命名空间 without 在顶部有一个命名空间会导致文件无法正确解析
    • 我理解你。所以我认为这是规范的缺失。
    【解决方案2】:

    您可以稍后在文件中切换到另一个命名空间,但如果您完全正在使用命名空间,则必须将命名空间声明为文件中的第一件事文件。即,这 不起作用 工作:

    <?php
    
    echo 'foo';
    
    namespace Bar;
    
    echo 'bar';
    

    【讨论】:

    • 感谢您的回答。但是这个命名空间在同一个文件中被取消了。 AnotherProject 命名空间不在此文件的顶部。这显然与A file containing a namespace must declare the namespace at the top of the file before any other code 相矛盾
    • 它没有。如果文件完全使用命名空间,则必须在文件顶部声明它。它并不是说以后不能再声明命名空间。
    • If the file uses a namespace at all, it must be declared at the top of the file. It does not say that no further namespace declaration may follow. 规范中没有规定。
    • 文档中也没有not指定。文档中写的内容是真实和正确的。一部分说你必须在文件顶部写命名空间声明,如果有的话,另一部分说你可以在下面写更多的命名空间声明。
    猜你喜欢
    • 2014-08-16
    • 2016-01-27
    • 2021-11-10
    • 1970-01-01
    • 2015-10-20
    • 2011-04-05
    • 2012-07-27
    • 2019-06-02
    • 1970-01-01
    相关资源
    最近更新 更多