Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP Global space
In PHP, when no namespace is explicitly defined, all classes, functions, and constants are placed in the global namespace. You can access global namespace elements from within any namespace by prefixing the name with a backslash (\).
Using Global Space Specification
When you're inside a namespace and need to call a global function, prefix it with \ to explicitly reference the global namespace ?
<?php
namespace test;
/* This function is test\fopen */
function fopen() {
/* Custom implementation */
$f = \fopen(...); // calls global fopen function
return $f;
}
?>
Global Namespace Example
Files without namespace declarations default to the global namespace ?
<?php // test1.php - no namespace, so it's in global space echo "Current namespace: '" . __NAMESPACE__ . "'<br>"; echo "This is the global namespace<br>"; ?>
Current namespace: '' This is the global namespace
Including Files from Namespaces
When you include a file from within a namespace, the included file still operates in its own namespace context ?
<?php // test2.php namespace testspace; include 'test1.php'; // test1.php runs in global namespace echo "Current namespace: '" . __NAMESPACE__ . "'<br>"; ?>
The output would be ?
Current namespace: '' This is the global namespace Current namespace: 'testspace'
Key Points
- Global namespace contains all elements without explicit namespace declaration
- Use
\prefix to access global functions from within namespaces - Included files maintain their original namespace context
-
__NAMESPACE__returns empty string in global namespace
Conclusion
The global namespace serves as the default container for all PHP elements. Using the backslash prefix allows you to explicitly access global functions and classes from within any namespace context.
