Home Backend Development PHP Tutorial What is a namespace

What is a namespace

Nov 14, 2017 am 10:34 AM
What name space

NamespaceOne of the clearest purposes is to solve the problem of duplicate names. PHP does not allow two functions or classes to have the same name, otherwise a fatal error will occur. In this case, it can be solved as long as you avoid naming duplication. The most common way is to agree on a prefix.

Example: There are two modules in the project: article and message board, each of which has a class Comment for processing user messages. Later, I may want to add some information statistics functions for all user messages. For example, I want to get the number of all messages. At this time, it is a good idea to call the methods provided by their Comments, but it is obviously not possible to introduce their respective Comment classes at the same time. The code will make errors, and rewriting any Comment in another place will also reduce maintainability. At this time, I can only reconstruct the class name. I agreed on a naming rule and added the module name in front of the class name, like this: Article_Comment, MessageBoard_Comment

As you can see, the name becomes very long, which means When I use Comment in the future, I will write more code (at least more characters). Moreover, if you want to add more integration functions to each module in the future, or call each other, you will need to reconstruct the names when duplicate names occur. Of course, this problem can be avoided by noticing this problem at the beginning of the project and specifying naming rules. Another solution may be to use namespace.

When declaring a namespace, the curly braces can not only contain variables, but also the following types:

Variables (can be initialized)

Constant

Function (can be a definition or declaration)

Structure

Class

Template

Name Space (namespaces can be nested)

Overview of the use of namespace :

Tips: In the following example, there are two files, one Demo. php, an index.php, the two files are in the same directory; write namespace and Demo class in the Demo.php file, index.php calls the Demo class in Demo.php; in the following example "Output result" means that the browser accesses index.php.

Simple example

Demo.php file code

<?php
  namespace DemoNameSpace;
 class Demo {   
     private $mysqlHandle;  
     public function construct(){     
     echo &#39;This is namespace of PHP demo ,The Demo magic constant "NAMESPACE" is &#39;.NAMESPACE; 
     }}?>
Copy after login

index.php file code

<?php 
 include &#39;Demo.php&#39;; 
 use DemoNameSpace\Demo;
 $DemoObj = new Demo();
 ?>
Copy after login

Output result 1: " This is namespace of PHP demo ,The Demo magic constant "NAMESPACE" is DemoNameSpace"

Explanation of the above example: There is a _NAMESPACE magic constant in Demo.php;"It contains the string of the current namespace name. In the global code, which is not included in any namespace, it contains an empty string. "

Continue with the example:

Do not change Demo.php, change index.php. The file is as follows:

<?php
include &#39;Demo.php&#39;;
$Demo = new Demo();
?>
Copy after login

Output result 2: "Fatal error: Class 'Demo' not found in F:\JJserver\demo\index.php on line 4"

This is common "Fatal error" message. According to the conventional PHP programming ideas, the output here should be consistent with "Output Result 1", but here it has a fatal error. Are you going crazy now? ~

line, first solve the crazy trouble, remove (or comment out) the statement "namespace DemoNameSpace;" in the Demo.php file, and everything will be normal. This is the most common way we usually write classes and call classes. I will not explain this situation without using namespace.

Comparing the two output situations of using namespace and not using namespace, and adding the definition of namespace to understand, the above fatal error situation is easy to understand. A namespace is defined in Demo.php, that is, after the namespace, the Demo class is defined, and then the Demo class is merged into the DemoNameSpace namespace. So when you want to call this Demo class, you must first call this DemoNameSpace namespace, that is, use the "useDemoNameSpace\Demo" statement in the index.php file.

2. A more complicated example

Demo.php file code

<?php
namespace DemoNameSpace; 
class Demo {  
  private $mysqlHandle;    
  public function construct(){        
  echo &#39;This is namespace of PHP demo ,The Demo magic constant "NAMESPACE" is &#39;.NAMESPACE;
  }} 
  namespace DemoNameSpace1; 
  const constDefine = &#39;JJonline1&#39;; 
  class Demo {   
  private $mysql; 
  const constDefine = &#39;JJonline2&#39;; 
  public function construct() { 
  echo &#39;The const constant outside class is: &#39;.constDefine; 
  echo &#39;===cut-off rule of god!!!!===&#39;;
  echo &#39;The const constant inside class is: &#39;.self::constDefine;
   }}?>
Copy after login

index.php file code

<?php 
include &#39;Demo.php&#39;; 
use DemoNameSpace1\Demo as Test; 
$Demo = new Test(); 
echo &#39;||||&#39;.DemoNameSpace1\constDefine;?>
Copy after login

Output result 3: "The const constant outside class is: JJonline1===cut-off rule of god!!!!===The const constant inside class is: JJonline2||||JJonline1”

这个结果在没有命名空间的时候,就直接报诸如“Fatal error: Cannot redeclare class Demo”的致命错误了。但运行没有报错,这也就是php5.3以后引入的命名空间的好处了,就诸如本文开头引用的官方解释中以不同目录下的相同文件名的文件可以存在一样是一个道理了。Demo.php文件中,定义的第一个名称叫做Demo的class类被归并到了DemoNameSpace的命名空间,而定义的第二个名称叫做Demo的class被归并到了DemoNameSpace1的命名空间,故而并不会出现不能重复定义某一个类的致命错误。以上的书写方法是要尽量避免的,因为类外部const常量名与类内部const常量名是一样的,很容易混淆,这里这样书写的目的就是看看不同位置申明的const常量,在调用时的情况;输出结果3已经很明显了,就不再多墨迹解释了。

Demo.php中DemoNameSpace1命名空间下还将const常量constDefine提出,拿到了定义class之外,这又要抓狂了,因为之前的知识是define定义全局常量,const定义class内部常量;这儿却将const拿出来玩了...具体就不再讲解了,Demo.php文件代码以及运行后的结果已经很明确的表明了相关知识。class内部定义的const只能在class的内部调用,采用self::constName形式,而class内部调用命名空间下、class外的const常量,则可以直接使用诸如define定义的常量一样使用。当需要使用该命名空间下、class外定义的const常量时,就使用类似路径形式的方式调用(index.php文件中的输出)。

该例子还有一点说明,就是在index.php中使用了use as语句,看index.php的代码,意义一目了然,new的一个class名称叫Test,但Test这个类并没有在Demo.php中定义,却没有出错,这就在于了use as语句了,具体意义不再解释。

通过上述的了解,namespace关键字可以将实现各种功能的class通过指定不同的命名空间分门别类存放,而且不同命名空间下的class可以同名;另外const常量定义也可以提出到class外部,当然也会有作用范围这么一个“内涵”~

总结下namespace的相关知识:

1、当前脚本文件的第一个命名空间前面不能有任何代码,例如如下代码就是会报致命错误的:

<?php
define("GREETING","Hello world!"); 
namespace DemoNameSpace;
class Demo { 
private $mysqlHandle; 
public function construct() { 
echo &#39;This is namespace of PHP demo ,The Demo magic constant "NAMESPACE" is &#39;.NAMESPACE;
 }}
 $Demo = new Demo();
 ?>
Copy after login

运行上述代码,会出现致命错误:“Fatal error: Namespace declaration statement has to be the very first statement in xxxx”

2、命名空间下直接new该命名空间中的class名称,可以省略掉use语法,这是php按脚本书写顺序执行导致的。例如如下代码是可以运行的

<?php
namespace DemoTest;
class Demo {   
 public function construct() {       
 echo &#39;this is a test script&#39;;   
 }}
 namespace DemoNameSpace;
 class Demo {   
 private $mysqlHandle;
 public function construct() { 
 echo &#39;This is namespace of PHP demo ,The Demo magic constant "NAMESPACE" is &#39;.NAMESPACE; 
 }}$
 Demo = new Demo();
 ?>
Copy after login

运行结果4:“This is namespace of PHP demo ,The Demo magic constant "NAMESPACE" is DemoNameSpace”

这个结果表明,同一脚本下new一个没有指定use哪个命名空间时,会顺着该脚本,使用最靠近new语句之前的一个命名空间中的class

3、公共空间:可以简单的理解,没有定义命名空间的方法(函数)、类库(class)、属性(变量)都默认归属于公共空间。这样就解释了为php5.3.0以前版本书写的代码大部分为何在php5.3.0及其以上版本还能正常运行的原因。另外:公共空间中的代码段被引入到某个命名空间下后,该公共空间中的代码段不属于任何命名空间!

命名空间的引入,让php面向对象编程更加的贴切,合理利用命名空间,也可以让项目文件规划,以上就是介绍命名空间的所有内容。

相关推荐:

实例详解PHP命名空间用法

PHP命名空间、性状与生成器相关介绍

php中命名空间与性状以及生成器新特性的详解

php namespace命名空间的定义方法实例详解

The above is the detailed content of What is a namespace. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to set up the keyboard boot function on a GIGABYTE motherboard (enable keyboard boot mode on GIGABYTE motherboard) How to set up the keyboard boot function on a GIGABYTE motherboard (enable keyboard boot mode on GIGABYTE motherboard) Dec 31, 2023 pm 05:15 PM

How to set up keyboard startup on Gigabyte's motherboard. First, if it needs to support keyboard startup, it must be a PS2 keyboard! ! The setting steps are as follows: Step 1: Press Del or F2 to enter the BIOS after booting, and go to the Advanced (Advanced) mode of the BIOS. Ordinary motherboards enter the EZ (Easy) mode of the motherboard by default. You need to press F7 to switch to the Advanced mode. ROG series motherboards enter the BIOS by default. Advanced mode (we use Simplified Chinese to demonstrate) Step 2: Select to - [Advanced] - [Advanced Power Management (APM)] Step 3: Find the option [Wake up by PS2 keyboard] Step 4: This option The default is Disabled. After pulling down, you can see three different setting options, namely press [space bar] to turn on the computer, press group

What is the best graphics card for i7 3770? What is the best graphics card for i7 3770? Dec 29, 2023 am 09:12 AM

What graphics card is good for Core i73770? RTX3070 is a very powerful graphics card with excellent performance and advanced technology. Whether you're playing games, rendering graphics, or performing machine learning, the RTX3070 can handle it with ease. It uses NVIDIA's Ampere architecture, has 5888 CUDA cores and 8GB of GDDR6 memory, which can provide a smooth gaming experience and high-quality graphics effects. RTX3070 also supports ray tracing technology, which can present realistic light and shadow effects. All in all, the RTX3070 is a powerful and advanced graphics card suitable for those who pursue high performance and high quality. RTX3070 is an NVIDIA series graphics card. Powered by 2nd generation NVID

Numerical distance based on machine learning: the distance between points in space Numerical distance based on machine learning: the distance between points in space Apr 11, 2023 pm 11:40 PM

This article is reprinted from the WeChat public account "Living in the Information Age". The author lives in the information age. To reprint this article, please contact the Living in the Information Age public account. In machine learning, a basic concept is how to judge the difference between two samples, so that the similarity and category information between the two samples can be evaluated. The measure to judge this similarity is the distance between two samples in the feature space. There are many measurement methods based on different data characteristics. Generally speaking, for two data samples x, y, define a function d(x, y). If it is defined as the distance between the two samples, then d(x, y) needs to satisfy the following basic properties : Non-negativity: d(x, y)&gt;=0 Identity: d(x, y)=0 ⇔ x=y pair

How to add swap space on Ubuntu 22.04 LTS How to add swap space on Ubuntu 22.04 LTS Feb 20, 2024 am 11:12 AM

Swap space plays an important role in Linux systems, especially when the system is low on memory. It acts as a backup memory storage space that helps the system run smoothly and maintain stability even under high load. This article provides you with a detailed guide to adding swap space on Ubuntu 22.04LTS to ensure that your system performance is optimized and can handle various workloads. Understanding Swap Space Swap space provides virtual memory that is used to supplement the system's physical RAM. When the system is low on RAM, the kernel swaps data to disk to prevent out-of-memory and system crashes. Linux systems commonly use swap space to handle this situation. Run multiple memory-intensive applications simultaneously to process very large files or data

Choosing the right tablet for music students Choosing the right tablet for music students Jan 10, 2024 pm 10:09 PM

Which tablet is suitable for musicians? The 12.9-inch speaker in Huawei’s iPad is a very good product. It comes with four speakers and the sound is excellent. Moreover, it belongs to the pro series, which is slightly better than other styles. Overall, ipad pro is a very good product. The speaker of this mini4 mobile phone is small and the effect is average. It cannot be used to play music externally, you still need to rely on headphones to enjoy music. Headphones with good sound quality will have a slightly better effect, but cheap headphones worth thirty or forty yuan cannot meet the requirements. What tablet should I use for electronic piano music? If you want to buy an iPad larger than 10 inches, I recommend using two applications, namely Henle and Piascore. Provided by Henle

Considerations for parameter order in C++ function naming Considerations for parameter order in C++ function naming Apr 24, 2024 pm 04:21 PM

In C++ function naming, it is crucial to consider parameter order to improve readability, reduce errors, and facilitate refactoring. Common parameter order conventions include: action-object, object-action, semantic meaning, and standard library compliance. The optimal order depends on the purpose of the function, parameter types, potential confusion, and language conventions.

What is the appropriate amount of remaining space on the c drive? What is the appropriate amount of remaining space on the c drive? Jun 27, 2023 pm 02:51 PM

The remaining space on the c drive is 50-80G which is more suitable. Since the system will generate junk files, cache files, etc. in the future, it is recommended to reserve at least 50GB-80GB of space for the C drive; if you are not used to choosing a path when installing software and do not clean your computer frequently, then at least 100GB is required. .

Introduction to the C drive space required for upgrading win11 Introduction to the C drive space required for upgrading win11 Dec 23, 2023 am 08:57 AM

As we all know, if the system disk occupied is too large after the system installation is completed, it may cause system lags, delays, and even file loss. Therefore, before you install the win11 system, you need to know how much C drive space is required to upgrade win11. Let’s take a look with the editor. How much C drive space is required to upgrade win11: Answer: Upgrading win11 requires 20-30GB of C drive space. 1. According to Microsoft’s win11 configuration requirements, you can see that win11 installation requires 64GB of hard drive space. 2. But in fact, generally speaking, there is no need for such a large space. 3. According to feedback from users who have already installed win11, the win11 upgrade requires about 20-30GB of C drive space. 4. But if our door only has

See all articles