Namespace is a way of encapsulating things. This abstract concept can be found in many places. For example, directories are used in operating systems to group related files, and they act as namespaces for the files in the directory.
Let me give you a simple example of a class:
Copy after login
In the above example, we have created a class in the Dojo namespace New class called Ninja. If we are not using namespaces and our application contains another class named Ninja, then we will get an error saying that we cannot redeclare the class.
Then namespace can solve this problem. We can create another class like this:
Copy after login
Now, if we include both files in our application, it will be easy to distinguish which Ninja class we want to use.
As an example, here is some code illustrating how we would use the Ninja class:
Copy after login
The two classes are different and may have different functionality, so the namespace allows us to use the same class name and differentiate them by their namespaces. You can also use the PHP use function to make your code more readable. For example, let's say we only want to use Ninja and not bring in Dojo\Ninja.
We can do this:
Copy after login
When we want to use another Ninja file, we can simply do the following:
use Training\Ninja as Ninja;
That’s it! Keep it simple!
The final point I want to make is that generally when using namespaces you want to follow the folder structure of the namespace so that it is easier to find the location of these files.
So our Training/Ninja.php file may exist in the Training folder.
#So, want to continue adding easy-to-remember and common class names to your project. Just remember to give them a namespace!
The above is the detailed content of How to use namespaces in PHP. For more information, please follow other related articles on the PHP Chinese website!