Tags
PHP
Asked 5 years ago
10 Oct 2018
Views 1144
sandip

sandip posted

how php namespace works ?

how to use php namespace?
i mean when i write code
namespace Csv\Exception;
what that means ?
Mitul Dabhi

Mitul Dabhi
answered Apr 25 '23 00:00

In PHP, namespaces are a way to prevent naming conflicts between classes, functions, and constants with the same name defined in different parts of a project or in different third-party libraries.

To define a namespace in PHP, the namespace keyword is used, followed by the desired namespace name. For example:


n

amespace MyNamespace;

class MyClass {
   // class code here
}

To use a class, function, or constant from another namespace, the use keyword is used to specify the namespace. Here's an example:



use AnotherNamespace\AnotherClass;

$object = new AnotherClass();

An alias can also be used to simplify the namespace reference. For instance:



use AnotherNamespace as AN;

$object = new AN\AnotherClass();

When using a namespace, PHP looks for the class, function, or constant in the current namespace first. If it's not found, PHP will look for it in the global namespace.

Namespaces can be nested using the backslash () character. For example:



namespace MyNamespace\SubNamespace;

class MyClass {
   // class code here
}

In this example, MyClass is part of the SubNamespace namespace, which is a sub-namespace of MyNamespace .
Post Answer