How to Create Namespace in PHP: Syntax and Examples
In PHP, you create a namespace using the
namespace keyword at the top of your PHP file before any other code. This groups related classes, functions, or constants under a unique name to avoid name conflicts.Syntax
The basic syntax to create a namespace in PHP is simple. You write namespace followed by the namespace name and a semicolon. This must be the first statement in your PHP file, before any other code except the declare statement.
- namespace: keyword to declare a namespace
- NamespaceName: the name you choose to group your code
- ;: ends the namespace declaration
php
<?php
namespace NamespaceName;
// Your classes, functions, or constants go here
Example
This example shows how to create a namespace called MyApp\Utils and define a class inside it. Then it shows how to use that class with the fully qualified name.
php
<?php namespace MyApp\Utils; class Helper { public static function greet() { return "Hello from Helper!"; } } // Using the class with full namespace echo \MyApp\Utils\Helper::greet();
Output
Hello from Helper!
Common Pitfalls
Common mistakes when using namespaces in PHP include:
- Placing the
namespacedeclaration after other code likeechoorusestatements. - Forgetting to use the fully qualified name or
usestatement when accessing classes from a namespace. - Using backslashes incorrectly in namespace names or class references.
Here is an example of a wrong and right way to use namespaces:
php
<?php // Wrong: namespace after code // echo "Hi"; // namespace MyApp; // Right: namespace MyApp; class Test {} // Accessing with use statement use MyApp\Test; $obj = new Test();
Quick Reference
| Concept | Description |
|---|---|
| namespace | Keyword to declare a namespace |
| Namespace name | Unique name to group code, e.g., MyApp\Utils |
| Placement | Must be first statement in the file |
| Access | Use fully qualified name or 'use' keyword |
| Separator | Backslash (\) separates namespace parts |
Key Takeaways
Declare namespaces at the very top of your PHP file before any other code.
Use the 'namespace' keyword followed by your chosen namespace name and a semicolon.
Access namespaced classes with their full name or import them using 'use'.
Avoid placing any output or code before the namespace declaration.
Use backslashes (\) to separate parts of a namespace.