0
0
PhpHow-ToBeginner · 3 min read

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 namespace declaration after other code like echo or use statements.
  • Forgetting to use the fully qualified name or use statement 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

ConceptDescription
namespaceKeyword to declare a namespace
Namespace nameUnique name to group code, e.g., MyApp\Utils
PlacementMust be first statement in the file
AccessUse fully qualified name or 'use' keyword
SeparatorBackslash (\) 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.