What's the benefit of namespaces in PHP? I've worked on multiple MVC systems and haven't found much use for them. I'm reading about them here.... is it a problem of sorts that I've never used them? Is it the kind of thing that is a good coding standard to always use?
In the PHP world, namespaces are designed to solve two problems that authors of libraries and applications encounter when creating re-usable code elements such as classes or functions: Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.
The biggest advantage of using namespace is that the class names which are declared in one namespace will not clash with the same class names declared in another namespace. It is also referred as named group of classes having common features.
The use keyword allows the developers to shorten the namespace. The namespace once created can include various functionalities which can be used in controllers and various classes.
In an operating system, an example of namespace is a directory. Each name in a directory uniquely identifies one file or subdirectory. As a rule, names in a namespace cannot have more than one meaning; that is, different meanings cannot share the same name in the same namespace.
Like any other languages, namespaces allow ambigious names / classes with same name to co-exists while being in two different namespaces.
For example Table
class can be referring to a table in a persistent database and a HTML table. I can put namespaces to specifically use the exact table that I want, i.e. \Model\Table
and \View\Table
respectively.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With