在一个文件中声明两个名称空间 [英] Declaring two namespaces in the one file

查看:81
本文介绍了在一个文件中声明两个名称空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

php reference

命名空间是使用namespace关键字声明的.一个文件包含 名称空间必须在文件顶部声明名称空间,然后才能 其他任何代码-除了一个例外:declare关键字.

Namespaces are declared using the namespace keyword. A file containing a namespace must declare the namespace at the top of the file before any other code - with one exception: the declare keyword.

但是,在参考文献中,我们还有以下代码片段:

But further we've the following code snippet in the reference:

<?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() { /* ... */  }
?>

推荐答案

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

One is declared at the top as first three lines under MyProject referes to MyProject namespace whereas other three under AnotherProject refers to AnotherProject namespace. If at least one namespace is declared as the top, file will be correctly parsed (namespace will be switched dinamically)

更清楚地说,您甚至可以做到这一点

Just to be more clear, you can even do that

<?php
namespace MyProject {

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

namespace AnotherProject {

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

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

However is strongly not recommended to declare two namespaces inside same php script

这篇关于在一个文件中声明两个名称空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆