After doing some research about namespacing in PHP I’m trying to figure out what are the real benefits other than having library items grouped together and re-use of the same class name.
What I don’t like about namespaces are these extra lines at the top of the file you’re calling the classes from ‘use core\whatever\class’, which you don’t have to do with the standard approach.
Also – something I couldn’t find information about – what happens in the situation where we need to use two classes with the same name, but in the different folders, which contain the same method name? We would still have to call the namespace, but how would the code figure out which method from which class should be used?
I’ve just started with namespaces so excuse me if this question seem to sound very basic.
Also – how does it work with the static methods – things like Helper class for instance – do I also have to indicate that I need this namespace ‘use core\whatever\Helper’ ?
If you have a large project with many classes, you’ll eventually run into naming conflicts. You have a
db/mysql/adapter.phpand ahttp/curl/adapter.php. To deal with this without namespaces, you have to give your classes unique names likeDb_Mysql_AdapterandHttp_Curl_Adapter, and any time you refer to these classes you need to use their full name.Namespaces allow you to name your classes
Db\Mysql\AdapterandHttp\Curl\Adapterand refer to them simply byAdapterin their local namespace, orMysql\AdapterandCurl\Adapterrespectively in other namespaces. This can save a lot of typing.Just browse through the source of Zend Framework version 1 vs. version 2 to see the difference.
If you’re in namespace
Db\Mysql,Adapter::foo()refers toDb\Mysql\Adapterand\Http\Curl\Adapter::foo()would refer to the other one. You can also alias the class at the top of your file, if you don’t want to write out the whole name all the time: