Tutorialspoint.dev

PHP | Namespace

Like C++, PHP Namespaces are the way of encapsulating items so that same names can be reused without name conflicts.

  • It can be seen as an abstract concept in many places. It allows redeclaring the same functions/classes/interfaces/constant functions in the separate namespace without getting the fatal error.
  • A namespace is a hierarchically labeled code block holding a regular PHP code.
  • A namespace can contain valid PHP code.
  • Namespace affects following types of code: classes (including abstracts and traits), interfaces, functions, and constants.
  • Namespaces are declared using the namespace keyword.

A namespace must be declared the namespace at the top of the file before any other code – with one exception: the declare keyword.

<?php 
namespace MyNamspaceName {
   
    // Regular PHP code 
    function hello() 
    {
        echo 'Hello I am Running from a namespace!';
    }
}
?>

If namespace is declared globally, then declare it without any name.



<?php 
namespace {
   
    // Global space!
}
?>

Multiple namespaces can be declared within a single PHP code.

<?php
namespace MyNamespace1 {
   
}
    
namespace MyNamespace2 {
   
}
    
namespace {
   
}
?>

A namespace is used to avoid conflicting definitions and introduce more flexibility and organization in the code base. Just like directories, namespace can contain a hierarchy know as subnamespaces. PHP uses the backslash as its namespace separator.

Example:

<?php
namespace MyNamespaceName;
function hello() 
    {
        echo 'Hello I am Running from a namespace!';
    }
    
// Resolves to MyNamespaceNamehello
hello();
  
// Explicitly resolves to MyNamespaceNamehello
namespacehello();
?>

Aliasing in Namespaces

Importing is achieved by using the ‘use’ keyword. Optionally, It can specify a custom alias with the ‘as’ keyword.
Example:

<?php
namespace MyNamespaceName;
    
require 'project/database/connection.php';
    
use ProjectDatabaseConnection as Connection;
    
$connection = new Connection();
    
use ProjectDatabase as Database;
    
$connection = new DatabaseConnection();
?>

It is possible to dynamically call namespaced code, dynamic importing is not supported.

<?php
namespace OtherProject;
    
$title = 'geeks';
    
// This is valid PHP
require 'project/blog/title/' . $title . '.php';
    
// This is not
use ProjectBlog itle$title;
?>

Reference : http://php.net/manual/en/language.namespaces.php



This article is attributed to GeeksforGeeks.org

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter