Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Files and Namespaces Scope

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?
like image 592
J Johnson Avatar asked Mar 06 '13 05:03

J Johnson


1 Answers

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();
like image 133
Emery King Avatar answered Oct 19 '22 19:10

Emery King