Declaring two namespaces in the one file

2019-09-20 16:17发布

问题:

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';