search

What is a namespace

Nov 14, 2017 am 10:34 AM
Whatnamespace

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
How do you set the session cookie parameters in PHP?How do you set the session cookie parameters in PHP?Apr 22, 2025 pm 05:33 PM

Setting session cookie parameters in PHP can be achieved through the session_set_cookie_params() function. 1) Use this function to set parameters, such as expiration time, path, domain name, security flag, etc.; 2) Call session_start() to make the parameters take effect; 3) Dynamically adjust parameters according to needs, such as user login status; 4) Pay attention to setting secure and httponly flags to improve security.

What is the main purpose of using sessions in PHP?What is the main purpose of using sessions in PHP?Apr 22, 2025 pm 05:25 PM

The main purpose of using sessions in PHP is to maintain the status of the user between different pages. 1) The session is started through the session_start() function, creating a unique session ID and storing it in the user cookie. 2) Session data is saved on the server, allowing data to be passed between different requests, such as login status and shopping cart content.

How can you share sessions across subdomains?How can you share sessions across subdomains?Apr 22, 2025 pm 05:21 PM

How to share a session between subdomains? Implemented by setting session cookies for common domain names. 1. Set the domain of the session cookie to .example.com on the server side. 2. Choose the appropriate session storage method, such as memory, database or distributed cache. 3. Pass the session ID through cookies, and the server retrieves and updates the session data based on the ID.

How does using HTTPS affect session security?How does using HTTPS affect session security?Apr 22, 2025 pm 05:13 PM

HTTPS significantly improves the security of sessions by encrypting data transmission, preventing man-in-the-middle attacks and providing authentication. 1) Encrypted data transmission: HTTPS uses SSL/TLS protocol to encrypt data to ensure that the data is not stolen or tampered during transmission. 2) Prevent man-in-the-middle attacks: Through the SSL/TLS handshake process, the client verifies the server certificate to ensure the connection legitimacy. 3) Provide authentication: HTTPS ensures that the connection is a legitimate server and protects data integrity and confidentiality.

The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

See all articles

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

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor