【问题标题】:PHP: Namespaces in a single file with a global namespacePHP:具有全局命名空间的单个文件中的命名空间
【发布时间】:2012-03-05 16:11:49
【问题描述】:

我有一个文件,它需要()的命名空间,例如:

<?php
require_once('Beer.php');   // This file contains the Beer namespace

$foo = new Beer\Carlsburg();
?>

我想将 Beer 命名空间直接放在同一个文件中,就像这个(不工作的)示例:

<?php
namespace Beer {
    class Carlsburg {}
}

$foo = new Beer\Carlsburg();
?>

但是,PHP 解释器抱怨 No code may exist outside of namespace。因此,我可以将 $foo 声明包装在命名空间中,但是我还必须将 Beer 包装在该命名空间中才能访问它!这是我试图避免的一个工作示例:

<?php
namespace Main\Beer {
    class Carlsburg {}
}

namespace Main {
    $foo = new Beer\Carlsburg();
}
?>

有没有办法在文件中包含Beer 命名空间的代码,但$foo 声明包装在它自己的命名空间中(将其保留在全局命名空间中)?

谢谢。

【问题讨论】:

  • 您应该将 Heineken 作为命名空间!

标签: php namespaces


【解决方案1】:

你应该使用全局命名空间:

<?php
namespace Beer {
    class Carlsburg {}
}


namespace { // global code
    $foo = new Beer\Carlsburg();
}
?>

看这里->http://php.net/manual/en/language.namespaces.definitionmultiple.php

【讨论】:

  • 这行不通,除非你写$foo = new Main\Beer\Carlsburg();
【解决方案2】:

试试这个

namespace Beer {
  class Carlsburg {}
}

//global scope 
namespace {
  $foo = new Beer\Carlsburg();
}

根据Defining multiple namespaces in the same file中的示例#3

【讨论】:

    【解决方案3】:

    随便写吧,它没有“名字”:

    <?php
    namespace Main\Beer {
        class Carlsburg {}
    }
    
    namespace {
        use Main\Beer;
        $foo = new Beer\Carlsburg();
    }
    ?>
    

    Demo 并查看Defining multiple namespaces in the same fileDocs

    【讨论】:

      【解决方案4】:

      尝试在命名空间名称前放置一个反斜杠:

      $beer = new \Beer\Carlsberg();
      

      最初的反斜杠被翻译为“全局命名空间”。如果不放前导反斜杠,则将类名转换为当前命名空间。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-11-22
        • 1970-01-01
        • 2012-11-07
        • 2013-02-07
        • 1970-01-01
        • 1970-01-01
        • 2012-08-06
        相关资源
        最近更新 更多