I recently started using namespaces in PHP. When I first saw them, I thought that their syntax was ugly and I'd never use them. However, I created an autoloader (spl_autoload_register) that makes it so that I never have to write an include/require statement again.
I like namespaces, but is there any objective benefit over include/require statements, or are they the exact same method to accomplish the same goal?
Best Answer
Namespaces are not just for autoloading classes. They also prevent naming conflicts. In fact, that's their primary purpose.
Say you have a project that needs a class named
User
, to store info about users of your application, but a plugin also uses a (different) class namedUser
to store information. Namespaces let you create your class within one namespace (say,MyApp
) and let the plugin use another namespace (say,CoolPlugin
). Code within theMyApp
space can just refer toUser
(e.g.,new User();
), and so can code in theCoolPlugin
space; each will get the expected result. When you need to use code from another namespace, you just prefix it. For example, code in theCoolPlugin
space can access theUser
class inMyApp
vianew \MyApp\User();
The alternative is that every class needs a complex name everywhere, such as
class MyApp_User
andclass CoolPlugin_User
. Namespaces let you simplify things most of the time and avoid naming conflicts all of the time.Edit: To answer the question, "Is there any performance difference between the two?"
Not a meaningful one, no. I haven't benchmarked it, but there is probably a difference on the nanosecond level. That said, sacrificing code quality for super-small performance tweaks is not a good strategy, so you should use namespaces regardless. For benchmarks of similar kinds of problems, see PHPbench.com and this StackOverflow answer.
Your code needs to be incredibly tight and incredibly time-sensitive (think high-frequency trading or managing nuclear reactions) before you need to worry about micro-optimizing it in this kind of context. If it really is that time-sensitive, you should probably be coding in c or even assembly, not interpreted languages like PHP.