0
0
PHPprogramming~5 mins

Global namespace access in PHP

Choose your learning style9 modes available
Introduction

Global namespace access lets you use functions, classes, or constants defined outside any namespace. It helps avoid confusion when you have code inside namespaces but want to use global code.

When you write code inside a namespace but want to call a built-in PHP function like strlen().
When you have a class inside a namespace but want to create an object of a class defined in the global space.
When you want to use a global constant inside a namespaced file.
When you want to avoid naming conflicts between your namespace and global code.
Syntax
PHP
<?php
namespace MyNamespace;

// Access global function
\strlen('text');

// Access global class
$obj = new \DateTime();

// Access global constant
$value = \PHP_VERSION;
?>

The backslash \ before a name tells PHP to look in the global namespace.

Without the backslash, PHP looks inside the current namespace.

Examples
This calls the global strlen function even though the code is inside the MyApp namespace.
PHP
<?php
namespace MyApp;

// Calls global strlen function
$length = \strlen('hello');
echo $length;
This creates a DateTime object from the global namespace inside a namespaced file.
PHP
<?php
namespace MyApp;

// Create global DateTime object
$date = new \DateTime();
echo $date->format('Y-m-d');
This prints the PHP version constant from the global namespace.
PHP
<?php
namespace MyApp;

// Use global constant
echo \PHP_VERSION;
Sample Program

This program shows the difference between calling a function inside the namespace and calling the global function using the backslash. It also creates a global DateTime object and prints the PHP version.

PHP
<?php
namespace Example;

function strlen($str) {
    return "Namespaced strlen called";
}

// Call namespaced strlen
echo strlen('test') . "\n";

// Call global strlen
echo \strlen('test') . "\n";

// Create global DateTime object
$date = new \DateTime();
echo $date->format('Y-m-d') . "\n";

// Print global constant
echo \PHP_VERSION . "\n";
OutputSuccess
Important Notes

Always use the leading backslash \ to access global code inside namespaces.

If you forget the backslash, PHP will look inside the current namespace and may cause errors or unexpected results.

Summary

Global namespace access uses a leading backslash \ to call global functions, classes, or constants inside namespaces.

This helps avoid naming conflicts and ensures you use the intended global code.