Home  >  Article  >  Backend Development  >  What is a namespace

What is a namespace

肚皮会动
肚皮会动Original
2017-11-14 10:34:002072browse

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; 
     }}?>

index.php file code

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

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();
?>

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;
   }}?>

index.php file code

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

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();
 ?>

运行上述代码,会出现致命错误:“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();
 ?>

运行结果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:
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