What are namespaces and how to use it in PHP?
In PHP, a namespace is a way to encapsulate and group related classes, functions, and constants to avoid name conflicts in larger applications or when integrating external libraries.
Why Use Namespaces?
Imagine you are using two libraries that both have a class named Database
. Without namespaces, PHP wouldn’t know which one you’re referring to, leading to a naming conflict. Namespaces solve this by allowing you to qualify names.
Example:
<?php
namespace MyApp;
class User {
public function sayHello() {
return "Hello from User!";
}
}
?>
To use the class:
<?php
require 'User.php';
$user = new \MyApp\User();
echo $user->sayHello();
?>