PSR | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

PSR

How does PHP "namespace" and the "use" operator really works? Except for the dos and don'ts, how does it find the file I need?

13th Aug 2018, 8:54 PM
Emmanuel Lanuzo
Emmanuel Lanuzo - avatar
1 Answer
+ 1
As I know, it doesn't find anything. Namespace is a tool to avoid conflictions of functions and classes in the code. Say, for example, we have the internal log() function (logarithm). If you want to declare a new function named log() (e.g. to logging into a file), PHP says "stop, we have one". So, you can declare it inside a namespace to prevent from errors. As you know, you must have the code (i.e. consisting your custom log() function inside your own namespace) inside your main code which is running, either by including it (e.g. using include) or writing it directly in the main file. By doing this, you say "Hey PHP, save this namespace with these functions/classes inside it as I may need later". Then, if you use "use" keyword, you will say "I want to use my code with this namespace, so as I defined it, there would be no errors". As a result, you can't use a non-exist code (e.g. namespace declarations) to let PHP find it.
24th Aug 2018, 2:15 AM
$machitgarha
$machitgarha - avatar