Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resetting a namespace in PHP?

Tags:

namespaces

php

How can I "reset" a namespace to the global one? Given the following code:

namespace foo;
include 'myfile.php';

myfile.php will now try to load all of its classes in the foo namespace, even though its classes are in the global namespace. Now it wouldn't be a big deal to swap the order of those lines, but how would I deal with myfile.php having an autoloader? It will try to load the classes in namespace foo.

like image 541
ryeguy Avatar asked Aug 10 '09 17:08

ryeguy


2 Answers

Namespaces work on a per-file basis. If myfile.php doesn't declare any namespace then everything in it will belong to the global namespace, regardless of the namespace in which include was used.

Long story short, namespace declarations only apply to their own file, not includes.

like image 144
Josh Davis Avatar answered Oct 06 '22 01:10

Josh Davis


myfile.php should declare the namespace that it wants to be in. If you want to ensure that myfile.php loads in the global namespace, I believe you can put

namespace // empty namespace means global
{
}

around the body of myfile.php. Make sure that you use the braces, or else you'll redefine the rest of the file in which myfile.php is included to also be in the global namespace.

like image 38
JSBձոգչ Avatar answered Oct 05 '22 23:10

JSBձոգչ