Declaring two namespaces in the one file

独自空忆成欢 提交于 2019-12-13 22:32:01

问题


As said in the php reference

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

回答1:


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

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




回答2:


You can switch to another namespace later on in the file, but if you are using namespaces at all, you have to declare a namespace as the first thing in the file. I.e., this does not work:

<?php

echo 'foo';

namespace Bar;

echo 'bar';


来源:https://stackoverflow.com/questions/22606792/declaring-two-namespaces-in-the-one-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!