Home  >  Article  >  Backend Development  >  How to use namespaces in PHP

How to use namespaces in PHP

藏色散人
藏色散人Original
2019-01-23 14:56:555877browse

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.

How to use namespaces in PHP

Let me give you a simple example of a class:

<?php 

namespace Dojo;

class Ninja
{

}

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:

<?php 

namespace Training;

class Ninja
{

}

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:

 <?php

// require both of our ninja classes
require "Dojo/Ninja.php";
require "Training/Ninja.php";

// create a new Ninja in the Dojo namespace
$ninja1 = new Dojo\Ninja();

// create a new Ninja in the Training namespace
$ninja2 = new Training\Ninja();

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:

<?php

// require both of our ninja classes
require "Dojo/Ninja.php";
require "Training/Ninja.php";

use Dojo\Ninja as Ninja;

$my_ninja = new Ninja();

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.

How to use namespaces in PHP

#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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn