OOP

PHP Namespaces

PHP Namespaces

PHP namespaces organize code, preventing name conflicts.

What are PHP Namespaces?

PHP namespaces are a way to encapsulate items such as classes, interfaces, functions, and constants. This organization helps prevent name conflicts in large codebases by allowing the same name to be used for different items in different namespaces.

Declaring a Namespace

To declare a namespace, use the namespace keyword at the top of your PHP file. This keyword tells PHP which namespace the enclosed code belongs to.

Here's a simple example:

Using Namespaces

Once a namespace is declared, you can reference the code within it by using the fully qualified name, which includes the namespace. This is particularly useful when you need to differentiate between two classes with the same name in different namespaces.

For example:

To use these classes, you would specify the full namespace:

Namespace Aliasing

Namespace aliasing allows you to import a namespace or a class within it under a different name using the use keyword. This can make your code more readable or resolve conflicts between two namespaces.

Example:

Global Namespace

By default, all code is in the global namespace until a namespace is declared. You can access global functions or classes from within a namespace by prefixing them with a backslash \.

Example: