PHP Tutorial
PHP Flow Control
PHP Functions
PHP String
PHP Array
PHP Date Time
PHP Object Oriented
Regular Expression
PHP Cookie & Session
PHP Error & Exception handling
MySQL in PHP
PHP File Directory
PHP Image Processing
Namespaces in PHP are a way to encapsulate items like classes, interfaces, functions, and constants. A namespace is designed to overcome the problem of naming collisions between code entities. For instance, if you're using a class of the same name from two different libraries, placing them in different namespaces can avoid the collision.
Here is an example of how to declare a namespace:
namespace MyNamespace; class MyClass { public function sayHello() { return "Hello, world!"; } }
To access this class from outside of the namespace, you prepend the namespace to the class name:
$obj = new MyNamespace\MyClass(); echo $obj->sayHello(); // Outputs: Hello, world!
You can also declare sub-namespaces using the backslash \
:
namespace MyNamespace\SubNamespace; class MyClass { // ... }
To access this class from outside of the namespace, you include the sub-namespace in the class name:
$obj = new MyNamespace\SubNamespace\MyClass();
The use
keyword can be used to import a class, interface, function, or constant from another namespace:
use MyNamespace\MyClass; $obj = new MyClass(); // No need to prepend the namespace
You can also use it to give a class, interface, function, or constant a nickname:
use MyNamespace\MyClass as ClassAlias; $obj = new ClassAlias(); // Use the alias instead of the full class name
Namespaces can also be used to group related classes, interfaces, functions, and constants. This can make your code easier to read and maintain, and it can prevent naming collisions.
Declaring and using namespaces in PHP:
// Declaring a namespace namespace MyNamespace; // Using the namespace class MyClass { public function myMethod() { echo "Hello from MyNamespace\MyClass!"; } } // Using the class from the namespace $obj = new MyNamespace\MyClass(); $obj->myMethod(); // Output: Hello from MyNamespace\MyClass!
Avoiding naming conflicts with PHP namespaces:
// Without namespace class MyClass { // ... } // With namespace namespace MyNamespace; class MyClass { // ... }
Aliasing and importing namespaces in PHP:
// Aliasing a namespace use MyNamespace\MyClass as MyAlias; // Using the aliased class $obj = new MyAlias();
Global and local namespaces in PHP:
namespace
keyword.// Global namespace class GlobalClass { // ... } // Local namespace namespace MyNamespace; class LocalClass { // ... }
Combining namespaces with classes and functions:
namespace MyNamespace; class MyClass { // ... } function myFunction() { // ... }
Autoloading classes with namespaces in PHP:
// Autoloader function spl_autoload_register(function ($class) { $class = str_replace("\\", "/", $class); include_once "$class.php"; }); // Using the class without manual inclusion $obj = new MyNamespace\MyClass();