How to Use Namespace in PHP: Syntax and Examples
In PHP, use
namespace at the top of your file to define a namespace, which helps organize code and avoid name conflicts. Access code inside a namespace using fully qualified names or the use keyword to import namespaces or classes.Syntax
The namespace keyword defines a namespace at the top of a PHP file. You can then use use to import classes or namespaces for easier access.
- namespace: Declares the namespace for the file.
- use: Imports classes or namespaces to avoid writing full names.
- Fully qualified name: Access a class with its full namespace path.
php
<?php namespace MyProject\Tools; class Helper { public static function greet() { return "Hello from Helper!"; } } // Using the class inside the same namespace echo Helper::greet();
Output
Hello from Helper!
Example
This example shows how to define a namespace, create a class inside it, and use the class from outside the namespace with the use keyword.
php
<?php // File: Tools/Helper.php namespace Tools; class Helper { public static function greet() { return "Hello from Tools\\Helper!"; } } // File: index.php namespace Main; use Tools\Helper; echo Helper::greet();
Output
Hello from Tools\Helper!
Common Pitfalls
Common mistakes when using namespaces include:
- Forgetting to declare
namespaceat the top of the file. - Not using the correct fully qualified name or missing the
usestatement. - Mixing global and namespaced code without proper referencing.
Always place the namespace declaration before any other code except the opening <?php tag.
php
<?php // Wrong: namespace declared after code // This will cause a fatal error // echo "Test"; // namespace MyApp; // Right way: namespace MyApp; echo "Test";
Output
Test
Quick Reference
| Keyword | Purpose | Example |
|---|---|---|
| namespace | Defines a namespace for the file | namespace MyApp; |
| use | Imports a class or namespace | use MyApp\Tools; |
| Fully qualified name | Access class with full path | \MyApp\Tools\Helper |
| Global namespace | Access global code inside namespace | \strlen('text') |
Key Takeaways
Declare
namespace at the top of your PHP file to organize code.Use
use to import namespaces or classes for simpler access.Always reference classes with their full namespace or import them to avoid errors.
Place the
namespace declaration before any other code except the opening tag.Namespaces help prevent name conflicts in larger PHP projects.