PHP Namespaces

Namespaces in PHP are a way to encapsulate items such as classes, interfaces, functions, and constants. They help avoid name collisions in larger applications and improve code organization.

Defining a Namespace

<?php
namespace MyProject;

class MyClass {
    public function sayHello() {
        return "Hello from MyClass!";
    }
}
?>

Explanation: This example defines a namespace called MyProject and a class MyClass within that namespace.

Using a Namespace

<?php
require 'MyClass.php'; // Include the file containing MyClass

use MyProject
MyClass;

$myClass = new MyClass();
echo $myClass->sayHello();
?>

Explanation: This code demonstrates how to use the use keyword to import the MyClass from the MyProject namespace and create an instance of it.

Namespace Aliases

<?php
use MyProject
MyClass as MC;

$myClass = new MC();
echo $myClass->sayHello();
?>

Explanation: This example shows how to create an alias for a namespace using the as keyword, allowing for shorter code when referencing classes.

Global Namespace

<?php
namespace MyProject;

function myFunction() {
    return "Hello from myFunction!";
}

// Accessing a global function
echo \myFunction(); // Calls the global function
?>

Explanation: To access a function in the global namespace, you can use the backslash \ before the function name.