Skip to content

Latest commit

 

History

History
77 lines (57 loc) · 2.46 KB

namespace.md

File metadata and controls

77 lines (57 loc) · 2.46 KB

➲ Namespace:

A namespace is a declarative region that holds a set of definitions under specified namespace for classes, functions, constants, etc. It is used to prevent naming conflicts across multiple PHP scripts, Especially working with large scale projects or including external libraries.

☴ Overview:

  1. Use of Namespace
  2. Global Namespace
  3. Declaration of Namespace
  4. Implementation of Namespace
  5. Namespace Alias
  6. Key Points

✦ Use of Namespace:

  • Avoid Naming Conflicts: It prevents name clashes among identifiers with same name.
  • Organize Code: It groups classes and functions into logical namespace.
  • Improve Code Readability: It makes, the code organized and easier to understand.

✦ Global Namespace:

If a class or function is not declared within a namespace, By default, it belongs to the global namespace.

✦ Declaration of Namespace:

Namespace for PHP script can be declared using the keyword namespace.

Example:

namespace MyProject\MyNamespace;

class MyClass {
    // ...
}

function myFunction() {
    // ...
}

✦ Implementation of Namespace:

If a class or function is declared within a namespace, It can not be accessed from global namespace. To use a class and function from a particular namespace, It can be implemented by either use the fully qualified name or import using the use keyword.

Example:

// Fully qualified name:
\MyProject\MyNamespace\MyClass::myStaticMethod();

$obj = new \MyProject\MyNamespace\MyClass();
$obj->myMethod();
// Using the `use` keyword:
use MyProject\MyNamespace\MyClass;

$obj = new MyClass();
$obj->myMethod();

✦ Namespace Alias:

To shorten the fully qualified name of namespace, by create an aliases for namespace with the as keyword.

use MyProject\MyNamespace as MPN;

$obj = new MPN\MyClass();

✦ Key Points:

  • Provide meaningful names for namespace declaration that reflect the project structure.
  • Avoid too many nested namespace.
  • Import namespaces with use keyword to improve code readability.
  • Use a PSR-4 autoloader to automatically load classes based on their namespaces.

⇪ To Top

❮ Previous TopicNext Topic ❯

⌂ Goto Home Page