Multiple Files and Namespaces Scope

2020-02-14 04:01发布

问题:

I'm pretty new to namespaces (and yes, I've read the PHP documentation namespaces section). I'm wondering what the scope of namespaces is with regard to multiple files. Is a namespace valid beyond one file when I include or require that file in a file that has global code? And furthermore, how does that affect the global code? Would I be forced to change anything syntax-wise with the global code.

For example, let's say I have file A.php. What I want to be able to have is this:

namespace A;
class Abc { ... }

And then let's say I have some file with global code, call it main.php:

include("A.php");
class Abc { ... }
$abc = new Abc(); // Should be global Abc, right?
$abcFromNameSpace = new A\Abc(); // Should be namespace Abc, right?
...

As a follow-up question, I'm also wondering what would happen with regard to scope if I were to include a file with namespaces inside another file with namespaces, as opposed to the above example, where main.php only has global code. Would that work like this:

namespace A;
class Abc { ... }

And then let's say I have some file with global code, call it B.php:

namespace B;
include("A.php");
class Abc { ... }
$abc = new B\Abc(); // Should be namepsace B Abc, right?
$abcFromNameSpace = new A\Abc(); // Should be namespace A Abc, right?

回答1:

Any time you refer to a class that is outside of the current file or class scope, you use its namespace:

<?php
namespace B;

$class = new \A\Abc();

But if you "use" the namespace in your script, you can leave it out:'

<?php
namespace B;

use A\Abc;

$class = new Abc();