0
0
PHPprogramming~5 mins

Namespace declaration syntax in PHP

Choose your learning style9 modes available
Introduction

Namespaces help organize code by grouping related classes, functions, and constants together. This avoids name conflicts when different parts of a program use the same names.

When you have many classes or functions and want to keep them organized.
When using third-party libraries that might have classes with the same names as yours.
When building large applications to avoid name clashes.
When you want to clearly separate different parts of your code by functionality.
Syntax
PHP
<?php
namespace Vendor\Package;

// Your code here
The namespace declaration must be the first statement in the PHP file, before any other code except the
Use backslashes (\) to separate levels in the namespace hierarchy.
Examples
This declares a namespace called MyApp and defines a class User inside it.
PHP
<?php
namespace MyApp;

class User {}
This declares a nested namespace MyApp\Models and defines a function getUser inside it.
PHP
<?php
namespace MyApp\Models;

function getUser() {}
This shows how to declare code in the global namespace explicitly using namespace { }.
PHP
<?php
namespace {
// global namespace
function globalFunction() {}
}
Sample Program

This program declares a namespace Shop\Products and defines a class Item with a method that returns a product name. Then it creates an object and prints the name.

PHP
<?php
namespace Shop\Products;

class Item {
    public function getName() {
        return "Book";
    }
}

$item = new Item();
echo $item->getName();
OutputSuccess
Important Notes

Namespaces help avoid conflicts but you must use the full name or import the namespace to access classes or functions outside the current namespace.

Use the use keyword to import namespaces for easier access.

Summary

Namespaces group related code to avoid name conflicts.

Declare namespaces at the top of PHP files using the namespace keyword.

Use backslashes to create nested namespaces.