Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use "global-namespace";

Tags:

namespaces

php

I just wonder if there's a way to make a class behave as if it is in global namespace using a "use" keyword, so this class would behave as namespaced class only from outside of the class. Something like:

namespace wherever\somewhere\deep\deep\inside;
use \; // root namespace.. note: this doesn't work
class stuff{
//....
}

anyone?

like image 479
enrey Avatar asked Jan 08 '13 11:01

enrey


2 Answers

Using the global namespace won't work the way you expect.

By default, you can reference a globally namespaced class by adding a backslash -- eg $x = new \PDO(...);. Trying to use \ won't change that.

If you want to drop the backslash from globally namespaced classes, you need to use each of them specifically. In namespaced PHP, any class reference that doesn't have a namespace is assumed to be in the current namespace, unless it is explicitly referenced by a use statement.

eg:

use \PDO, \SplFileObject;

now we can call new PDO(...) or new SplFileObject() without the backslash. But other global classes that aren't in the use would still need the backslash.

like image 92
SDC Avatar answered Oct 30 '22 01:10

SDC


You can access the global namespace if you use brackets like this:

namespace My\Space {
    function myScopedFunction() { .. }
}
namespace {
    function myGlobalFunction() { .. }
}
like image 3
cjohansson Avatar answered Oct 30 '22 00:10

cjohansson